Python is a high-level, general-purpose programming language known for its readability, simplicity, and versatility. It was created by Guido van Rossum in 1991 and has since become one of the most popular languages in the world.
Here are some key characteristics of Python:
Topics covered
In this short tutorial we will cover fundamental topics to understand Python from beginer to intermediate developer. After reading this page is a good idea to consider taking our advanced Python course that is hostet on Sage-Code main web-site.
if
, else
, and elif
statements to control program flow based on conditExplaions.for
and while
loops to iterate through sequences and repeat code blocks.These are just the foundational topics to get you started with Python syntax. As you progress, you will explore more advanced concepts like classes, objects, object-oriented programming, and exception handling.
This tutorial is created using AI (Gemini) and may not be perfect. We will continue to improve this tutorial in the future with help from students like yourself. Join Discord and GitHub to contribute. This tutorial is open source. If you conntinue reading and encounter errors, please report them and create work items for us to resolve them.
name
and Name
are distinct variables.if
statements and loops) are defined by consistent indentation (usually 4 spaces), not curly braces.#
for single-line comments and """
or '''
for multi-line comments.Data Types:
int
(integers), float
(decimals), complex
(real and imaginary parts).True
or False
.Operators:
+
, -
, *
, /
, //
(integer division), %
(remainder).==
, !=
, <
, >
, <=
, >=
.and
, or
, not
.=
, +=
, -=
, *=
, /=
, etc.Control Flow:
if
Statements: Decide which code to execute based on a condition:
if age >= 18:
print("You are eligible to vote.")
else
and elif
Statements: Provide alternative choices:
if grade >= 90:
print("Excellent!")
elif grade >= 80:
print("Good job!")
else:
print("Keep practicing!")
for
Loops: Repeat code for a sequence of steps:
for i in range(5): # Iterates 5 times
print(i)
while
Loops: Repeat code until a condition is met:
num = 1
while num <= 10:
print(num)
num += 1 # Increase num by 1
Functions:
Reusable blocks of code that perform a task:
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # Output: Hello, Alice!
Essential Tips:
Additional Considerations:
Explaining Python syntax is not yet good enaugh for you to understand Python. Therefore we will ceate examples and explain the code using AI. You can read all about Python in the documentation but using these examples you can dive deeper and have a better start. Let’s try our first example:
def factorial(n):
"""Calculates the factorial of a non-negative integer n.
Args:
n: The non-negative integer for which to calculate the factorial.
Returns:
The factorial of n, or None if n is negative.
Raises:
ValueError: If n is negative.
"""
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1 # Base case: factorial of 0 is 1
result = 1
for i in range(1, n + 1):
result *= i # Multiply result by each number from 1 to n
return result
# Test cases with assert statements
assert factorial(0) == 1, "factorial(0) should be 1"
assert factorial(5) == 120, "factorial(5) should be 120"
assert factorial(10) == 3628800, "factorial(10) should be 3628800"
# Print the results of 3 calls
print(f"factorial(0) = {factorial(0)}")
print(f"factorial(5) = {factorial(5)}")
print(f"factorial(10) = {factorial(10)}")
Explanation:
def factorial(n):
defines a function named factorial
that takes one argument n
.if n < 0:
checks for invalid input (negative numbers).raise ValueProgramError("n must be non-negative")
raises an error if input is invalid.if n == 0:
handles the special case where n
is 0, returning 1.result = 1
initializes a variable to store the factorial.for i in range(1, n + 1):
iterates from 1 to n
.result *= i
multiplies result
by each number in the range, calculating the factorial.return result
returns the calculated factorial.assert
statements check if the function produces expected results for specific inputs.print(f"factorial(x) = {factorial(x)}")
calls the function with different values and prints the results.Output:
factorial(0) = 1
factorial(5) = 120
factorial(10) = 3628800
Observe, the function factorial(n) is ending with statement: “return result”, that has an indentation of 4 spaces. The program continue with “assert”. There is nothing to tell you that the function dyefinition has ended. This is an inconvenient for beginners and this is one of the reasons I do not like Python.
Here’s a breakdown of Python’s fundamental data types, complete with explanations, examples, and code snippets:
Numbers:
int
) represent whole numbers without decimals, like 10
, -5
, or 42
.float
) represent numbers with decimals, like 3.14
, -2.718
, or 1.0e6
(scientific notation).complex
) represent numbers with real and imaginary parts, like 3 + 4j
or 5.2 - 1.8j
.Example:
age = 30 # int
price = 29.99 # float
complex_number = 3 + 2j # complex
Strings:
str
) represent sequences of characters, enclosed in single or double quotes ('hello'
or "world!"
).\
) to escape special characters like quotes or newlines.Example:
name = "Alice"
greeting = 'Hello, world!'
multiline_string = """This is a
multiline string"""
Lists:
list
) are ordered collections of items, enclosed in square brackets []
.Example:
fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "two", 3.0]
empty_list = []
Tuples:
tuple
) are similar to lists but immutable, meaning their elements cannot be changed after creation.()
, they are useful for data that shouldn’t be modified.Example:
coordinates = (10, 20) # Immutable
nested_tuple = (1, [2, 3], (4, 5))
Dictionaries:
dict
) are unordered collections of key-value pairs, enclosed in curly braces {}
.Example:
person = {"name": "Bob", "age": 35, "city": "New York"}
empty_dict = {}
Sets:
set
) are unordered collections of unique items, enclosed in curly braces {}
.Example:
unique_fruits = {"apple", "banana", "apple"} # Removes duplicates
numbers = {1, 2, 3, 2} # Keeps only unique values
Remember:
type()
function: print(type(age))
.By understanding these fundamental data types, you’ll have a solid foundation for building Python programs!
Here’s an explanation of data literals, global vs. local scope, and best practices for variables and constants in Python:
Data Literals:
10
, -5
, 0
3.14159
, -2.718
, 1.0e6
"hello"
, 'world'
, '''multiline string'''
True
, False
[1, 2, 3]
, ["apple", "banana"]
(10, 20)
, ("x", "y", "z")
{"name": "Alice", "age": 30}
, {}
{1, 2, 3}
, {"apple", "banana"}
Global and Local Scope:
PI = 3.14159 # Global variable
def calculate_area(radius):
area = PI * radius**2 # Can access PI here
return area
def greet(name):
greeting = "Hello, " + name # Local variable
print(greeting)
Best Practices:
ALL_CAPS
for constants by convention.Additional Tips:
While Python doesn’t have built-in arrays like some other languages, it offers powerful alternatives like lists, tuples, and dictionaries for storing and organizing data. Let’s break down each one:
1. Lists: The Flexible All-Rounders
Imagine lists like shopping carts. They’re mutable (you can add, remove, or change items), ordered (items have a specific sequence), and can hold different data types (numbers, strings, even other lists!).
Example:
fruits = ["apple", "banana", "orange"] # Create a list
fruits.append("mango") # Add an item
print(fruits[1]) # Access the second item ("banana")
Use lists when:
2. Tuples: The Immutable Champions
Think of tuples like museum exhibits. They’re immutable (you can’t modify them), ordered, and can also hold mixed data types. But once created, their contents are fixed.
Example:
coordinates = (10, 20) # Create a tuple
# coordinates[0] = 15 # This will raise an error (tuples are immutable)
print(coordinates[1]) # Access the second item (20)
Use tuples when:
3. Dictionaries: The Key-Value Keepers
Imagine dictionaries like phonebooks. They store key-value pairs, where the key uniquely identifies an item (like a name) and the value is the associated data (like a phone number). Dictionaries are mutable and can hold different data types for both keys and values.
Example:
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person["age"]) # Access the value for key "age" (30)
person["city"] = "London" # Update the city
Use dictionaries when:
Bonus Tip:
array
module provides array-like functionality for specific use cases (e.g., storing large numbers efficiently).Remember, choosing the right collection depends on your specific needs. Lists offer versatility, tuples ensure data integrity, and dictionaries excel in key-based lookups. So, experiment and find the perfect fit for your Python projects!
In Python, packages are like pre-built components that offer reusable code, modules, and functions. Think of them as modular tools you can integrate into your projects to save time and effort. Here’s a breakdown:
1. What are Packages in Python?
setup.py
or pyproject.toml
).2. What is a Package Manager?
3. Finding Packages:
pip search
command followed by keywords to find relevant packages on PyPI.4. Using Packages in Projects:
pip install <package_name>
.import <module_name>
.module_name.function_name()
).Examples:
numpy
for numerical computations: import numpy as np
requests
for making HTTP requests: import requests
matplotlib
for data visualization: import matplotlib.pyplot as plt
Tips:
pipreqs
to generate a requirements.txt
file listing project dependencies.By understanding packages and package managers, you can leverage the vast ecosystem of tools and libraries available in Python, making your development process more efficient and productive!
Built-in Packages in Python: Ready-to-Use Tools at Your Fingertips
While Python offers a rich ecosystem of third-party packages, it also comes with a set of valuable built-in packages, pre-installed and ready to use. These packages provide essential functionality for common tasks, saving you time and effort.
The io
Package: Your Gateway to File Input and Output
One of these built-in packages is the io
package, which empowers you to interact with files effectively. Here’s how to use it for reading and writing files:
1. Reading from Files:
with open("my_file.txt", "r") as file:
# Read the entire contents
contents = file.read()
print(contents)
with open("my_file.txt", "r") as file:
for line in file:
print(line, end="") # Print each line without extra newlines
2. Writing to Files:
with open("new_file.txt", "w") as file:
file.write("This is some new text.")
with open("existing_file.txt", "a") as file:
file.write("\nThis text is appended.")
Key Points:
with
statement ensures proper file closure, even if errors occur.file.read()
to read the entire content, file.readlines()
to read all lines into a list, or iterate through lines using a for
loop.file.write()
to write text to a file.Additional Tips:
io
package for tasks like seeking within a file (file.seek()
) and checking your current position (file.tell()
).with
statements) for clean resource management.By mastering the io
package and other built-in packages, you’ll tap into Python’s core capabilities and streamline your development process!
So far you have learned the basics of Python. If you enjoy reading so far, I’m proud of you. Next maybe you wish to study more. You can chose to follow the documentation or other mentors. We offer an advanced Python course, that will teach you again the basics and then enable introductions of advance topics.
Follow next: CSP04-Python
“Python is a beautiful language. It’s easy to learn and use, but it’s also very powerful. It’s one of the most popular languages in the world, and for good reason.” (Mark Zuckerberg, co-founder of Facebook)