Python short tutorial
Python Tutorial (Easy & Modern Features)
Python is known for its readability and simplicity. It's great for web development, data science, automation, and more.
1. "Hello, World!"
# This is a comment - Python ignores it
print("Hello, Python World!")
Explanation:
#
: Lines starting with#
are comments, used for explaining code.print()
: A built-in Python function to display output to the console."Hello, Python World!"
: A string literal (text enclosed in quotes).
2. F-Strings (Formatted String Literals) (Python 3.6+):
A fantastic way to embed variables directly into strings. Much cleaner than older methods.
name = "Bob"
age = 25
# Use an f-string to embed variables
message = f"Hello, my name is {name} and I am {age} years old."
print(message)
# You can also include expressions
pi = 3.14159
print(f"The value of pi is approximately {pi:.2f}") # Format to 2 decimal places
Explanation:
f"..."
: Thef
orF
before the quotes indicates it's an f-string.{variable_name}
: Place variable names or expressions inside curly braces{}
to insert their values.{pi:.2f}
:.2f
specifies formatting as a floating-point number (f
) with 2 decimal places.
3. Type Hinting (Python 3.5+):
Specifies the expected types for variables, function arguments, and return values. It doesn't enforce types strictly at runtime but improves code readability and helps static analysis tools catch errors early.
def add(a: int, b: int) -> int:
"""This function takes two integers and returns their sum."""
return a + b
result = add(5, 3)
print(f"The sum is: {result}")
def greet(name: str) -> None:
"""This function prints a greeting and doesn't return anything."""
print(f"Hello, {name}!")
greet("Alice")
Explanation:
a: int
: Specifies that variablea
is expected to be an integer.-> int
: Specifies that theadd
function is expected to return an integer.-> None
: Specifies that thegreet
function doesn't explicitly return anything (it implicitly returnsNone
).
4. Structural Pattern Matching (Python 3.10+):
A powerful way to match values against patterns, similar to switch
statements but much more flexible.
def process_point(point):
match point:
case (0, 0):
print("Point at the origin")
case (x, 0):
print(f"Point on the x-axis at x={x}")
case (0, y):
print(f"Point on the y-axis at y={y}")
case (x, y):
print(f"Point at ({x}, {y})")
case _: # Wildcard pattern - matches anything else
print("Unknown point format")
process_point((0, 0))
process_point((5, 0))
process_point((0, -2))
process_point((3, 4))
process_point("hello")
Explanation:
match point:
: Starts the pattern matching block.case (0, 0):
: Matches ifpoint
is exactly the tuple(0, 0)
.case (x, 0):
: Matches ifpoint
is a tuple with two elements, where the second is0
. The first element is assigned to the variablex
.case (x, y):
: Matches ifpoint
is a tuple with two elements, assigning them tox
andy
.case _:
: The wildcard case, matches if none of the previous patterns match.
5. Walrus Operator (:=
) (Python 3.8+):
Allows assigning values to variables within an expression. It can sometimes make code cleaner, especially when you need to re-use the result of an operation immediately.
data = [1, 2, 3, 4, 5]
# Without walrus operator
# n = len(data)
# if n > 3:
# print(f"List has {n} elements, which is more than 3.")
# With walrus operator
if (n := len(data)) > 3:
print(f"List has {n} elements, which is more than 3.")
Explanation:
(n := len(data))
: Assigns the result oflen(data)
ton
and returns that result, which is then used in theif
condition.
Running Python Code:
Save the code in a .py
file (e.g., my_script.py
). Open your terminal or command prompt, navigate to the directory where you saved it, and run:
python my_script.py # Or python3 my_script.py