Variables & Types
name = "Alice" # str
age = 30 # int
price = 9.99 # float
active = True # bool
items = [1, 2, 3] # list
coords = (10, 20) # tuple (immutable)
user = {"name": "Alice", "age": 30} # dict
unique = {1, 2, 3} # set
String Formatting
# f-strings (recommended)
f"Hello, {name}! Age: {age}"
f"Price: {price:.2f}"
f"{'hello':>20}" # Right-align
# .format()
"Hello, {}".format(name)
Lists
nums = [1, 2, 3, 4, 5]
nums.append(6) # Add to end
nums.insert(0, 0) # Insert at index
nums.pop() # Remove last
nums.remove(3) # Remove first occurrence
nums.sort() # Sort in place
sorted(nums) # Return sorted copy
nums[1:3] # Slice: [2, 3]
nums[::-1] # Reverse
Dictionaries
d = {"a": 1, "b": 2}
d["c"] = 3 # Add/update
d.get("x", 0) # Get with default
d.keys() # Dict keys
d.values() # Dict values
d.items() # Key-value pairs
{**d, "d": 4} # Merge (Python 3.9+: d | {"d": 4})
Comprehensions
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in nums if x % 2 == 0]
# Dict comprehension
word_len = {w: len(w) for w in words}
# Set comprehension
unique_chars = {c for c in "hello"}
Functions
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
# Lambda
double = lambda x: x * 2
# *args and **kwargs
def func(*args, **kwargs):
print(args) # Tuple of positional args
print(kwargs) # Dict of keyword args
Error Handling
try:
result = int("abc")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected: {e}")
finally:
print("Always runs")