Quick reference guide for Python. Essential syntax, control flow, data structures, and common patterns.
Hello World
print("Hello, World!") # The universal programmer's rite of passage.
Variables
x = 42 # integer
name = "Alice" # string
flag = True # boolean
pi = 3.14 # float
Control Flow
If/Else
if x > 10: # Colon is mandatory; indentation rules supreme
print("x is big")
else:
print("x is small")
if x > 10:
print("big")
elif x > 5:
print("medium")
else:
print("small")
For Loops
for i in range(5): # i goes from 0 to 4
print(i)
for item in [1, 2, 3]: # Iterate over list
print(item)
for i in range(0, 10, 2): # Start, stop, step
print(i) # Prints 0, 2, 4, 6, 8
While Loops
while x > 0: # Beware infinite loops
x -= 1
print(x)
Functions
def add(a, b): # 'def' starts the function
return a + b
print(add(2, 3)) # Call a function with parentheses
def greet(name="World"): # Default parameter
return f"Hello, {name}!"
greet() # Uses default
greet("Alice") # Overrides default
Lists / Dictionaries
Lists
nums = [1, 2, 3] # Lists are ordered, mutable
for n in nums:
print(n)
nums.append(4) # Add to end
nums.insert(0, 0) # Insert at index
nums.pop() # Remove and return last item
nums[0] # Access by index
nums[-1] # Last item (negative indexing)
nums[1:3] # Slice: items 1 to 2 (not 3)
Dictionaries
person = {"name": "Alice", "age": 30} # Key-value mapping
print(person["name"]) # Access via keys
person["city"] = "NYC" # Add new key-value
person.get("name") # Safe access (returns None if missing)
person.get("phone", "N/A") # With default value
for key, value in person.items(): # Iterate over key-value pairs
print(f"{key}: {value}")
Tuples
point = (3, 4) # Immutable ordered collection
x, y = point # Unpacking
Sets
unique = {1, 2, 3} # Unordered collection of unique items
unique.add(4) # Add item
unique.remove(2) # Remove item
String Operations
text = "Hello, World!"
text.upper() # "HELLO, WORLD!"
text.lower() # "hello, world!"
text.split(",") # ["Hello", " World!"]
text.replace("World", "Python") # "Hello, Python!"
f"Value: {x}" # f-string formatting
"Value: {}".format(x) # .format() method
List Comprehensions
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, ...]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
Error Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Can't divide by zero!")
except Exception as e:
print(f"Error: {e}")
finally:
print("This always runs")
File Operations
# Reading
with open("file.txt", "r") as f:
content = f.read()
lines = f.readlines()
# Writing
with open("file.txt", "w") as f:
f.write("Hello, World!")
# Appending
with open("file.txt", "a") as f:
f.write("New line\n")
Classes
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
person = Person("Alice", 30)
print(person.greet())
Tips
- Indentation *is* syntax — Python hates lazy spacing.
input()always returns a string; convert to int/float if needed:age = int(input("How old are you? "))
- Python is dynamically typed: flexible, but watch out for sneaky type errors.
- Everything is an object, even functions and classes.
range(5)goes 0..4, not 5 — the Pythonic gotcha.
- Use
withstatements for file operations — automatic cleanup.
- List comprehensions are faster and more Pythonic than loops for simple transformations.
- Use
enumerate()when you need both index and value:for i, item in enumerate(items): print(f"{i}: {item}")
- Use
zip()to iterate over multiple lists simultaneously:for name, age in zip(names, ages): print(f"{name} is {age}")
- Import modules with
import moduleor specific functions withfrom module import function.