Python Basics Cheatsheet
Core Python syntax, data structures, and idioms every developer needs to know — from variables to comprehensions.
· 8 min read · AI-generated
Variables & Types
# Dynamic typing — no declarations needed
name = "Alice"
age = 30
score = 98.6
active = True
nothing = None
# Type hints (optional but recommended)
name: str = "Alice"
age: int = 30
Strings
# f-strings (prefer over .format() or %)
greeting = f"Hello, {name}! You are {age} years old."
# Common string methods
s = " hello world "
s.strip() # "hello world"
s.upper() # " HELLO WORLD "
s.split() # ["hello", "world"]
", ".join(["a", "b", "c"]) # "a, b, c"
"hello".startswith("he") # True
Lists
items = [1, 2, 3, 4, 5]
items.append(6) # add to end
items.insert(0, 0) # insert at index
items.pop() # remove & return last
items.pop(0) # remove & return at index
items.remove(3) # remove first occurrence of value
len(items) # length
items[0] # first element
items[-1] # last element
items[1:3] # slice [2, 3]
items[::-1] # reversed copy
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
Dictionaries
person = {"name": "Alice", "age": 30}
person["name"] # "Alice"
person.get("missing", "default") # safe access
person["city"] = "NYC" # add/update key
del person["age"] # delete key
"name" in person # True
person.keys() # dict_keys
person.values() # dict_values
person.items() # dict_items (key, val tuples)
# Dict comprehension
squares = {x: x**2 for x in range(5)}
Control Flow
# if / elif / else
if age >= 18:
print("adult")
elif age >= 13:
print("teen")
else:
print("child")
# Ternary
label = "adult" if age >= 18 else "minor"
# for loop
for item in items:
print(item)
for i, item in enumerate(items): # with index
print(i, item)
for k, v in person.items(): # dict iteration
print(k, v)
# while loop
count = 0
while count < 5:
count += 1
Functions
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
# *args and **kwargs
def log(*args, **kwargs):
print(args, kwargs)
# Lambda
double = lambda x: x * 2
# Type annotations
from typing import Optional, List
def find(items: List[str], target: str) -> Optional[int]:
try:
return items.index(target)
except ValueError:
return None
Error Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError) as e:
print(f"Type or value error: {e}")
else:
print("No error!")
finally:
print("Always runs")
File I/O
# Read
with open("file.txt", "r") as f:
content = f.read() # entire file
lines = f.readlines() # list of lines
# Write
with open("out.txt", "w") as f:
f.write("Hello\n")
# Append
with open("log.txt", "a") as f:
f.write("new line\n")
Useful Built-ins
sorted([3, 1, 2]) # [1, 2, 3]
sorted(items, key=lambda x: x["age"]) # sort by key
reversed([1, 2, 3]) # iterator
zip([1, 2], ["a", "b"]) # [(1, "a"), (2, "b")]
map(str, [1, 2, 3]) # map object
filter(lambda x: x > 2, [1, 2, 3]) # filter object
any([False, True, False]) # True
all([True, True, False]) # False
sum([1, 2, 3]) # 6
min([3, 1, 2]) # 1
max([3, 1, 2]) # 3