01 Variables and types
No keyword, no type declaration. The name exists from the moment you assign to it.
name = "Ada" # str
age = 36 # int
height = 1.7 # float
active = True # bool - capital T
nothing = None # the "no value" value
plants = ["fern"] # list
plant = {"id": 1} # dict
x, y = 3, 4 # several at once
type(age) # <class 'int'>
int("42") # 42
float("3.14") # 3.14
str(42) # "42"
int(3.9) # 3 - truncates, does not round
02 Operators
/ always produces a float. // drops the remainder, % keeps only the remainder.
arithmetic and comparison
03 Strings
Immutable: every method returns a new string rather than changing the original.
name = "Ada Lovelace"
len(name) # 12
name[0] # "A"
name[-1] # "e"
name[0:3] # "Ada" start up to, not including, stop
name[4:] # "Lovelace"
name[::-1] # reversed
name.upper() name.lower() name.title()
name.strip() # trim whitespace both ends
name.replace("a", "o")
name.split(" ") # ["Ada", "Lovelace"]
" ".join(["a", "b"]) # "a b"
name.startswith("Ada") name.endswith("e")
"Ada" in name # True
f"{name} is {age}" # f-string
f"{price:.2f}" # 2 decimal places
f"{count=}" # prints count=3 - good for debugging
04 Lists
Ordered and changeable. Positions start at zero; a negative index counts from the end.
plants = ["fern", "cactus", "ivy"]
plants[0] # "fern"
plants[-1] # "ivy"
plants[0:2] # ["fern", "cactus"]
len(plants) # 3
plants.append("aloe") # add to the end
plants.insert(0, "oak") # add at a position
plants.remove("ivy") # remove by value
plants.pop() # remove and return the last
plants.pop(0) # remove and return by position
plants.sort() # sorts in place, returns None
sorted(plants) # returns a new sorted list
plants.reverse()
"fern" in plants # True
plants.index("cactus") # 1
plants.count("fern") # 1
copy = plants[:] # a real copy, not another name
nums = [4, 7, 2]
sum(nums) min(nums) max(nums)
05 Dictionaries
Named values. Use .get() when the key might be missing — it returns None instead of raising KeyError.
plant = {"name": "fern", "room": "kitchen", "days": 7}
plant["name"] # "fern"
plant["missing"] # KeyError
plant.get("missing") # None
plant.get("missing", 0) # 0 as a fallback
plant["days"] = 10 # change, or add if new
del plant["room"]
"name" in plant # True
plant.keys() # the names
plant.values() # the values
plant.items() # pairs
for key, value in plant.items():
print(key, value)
# A list of dictionaries is the shape most real data takes
plants = [
{"name": "fern", "days": 7},
{"name": "cactus", "days": 30},
]
06 if, elif, else
Colon then indent. Order your branches from most specific to least, or the broad one catches everything first.
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
else:
grade = "F"
# On one line, when it assigns
label = "item" if count == 1 else "items"
# Combining
if age >= 18 and has_id:
if not finished:
if room in ("kitchen", "office"):
# Falsy: 0, 0.0, "", [], {}, None, False. Everything else is truthy.
if plants: # "if the list is not empty"
if value is None: # test for None with is, not ==
07 Loops
Build a list by starting empty and appending, or say the same thing on one line with a comprehension.
for plant in plants:
print(plant)
for i in range(5): # 0 1 2 3 4
for i in range(2, 6): # 2 3 4 5
for i in range(10, 0, -2): # 10 8 6 4 2
for i, plant in enumerate(plants): # index and item
for name, room in zip(names, rooms): # two lists together
for key, value in plant.items(): # a dictionary
while count > 0:
count -= 1 # something must change the condition
break # leave the loop now
continue # skip to the next pass
# Comprehensions
[n * 2 for n in nums]
[n for n in nums if n > 4]
[p["name"] for p in plants]
08 Functions
return hands a value back. A function with no return gives None.
def greet(name, greeting="Hello"):
"""One line saying what it does."""
return f"{greeting}, {name}!"
greet("Ada") # "Hello, Ada!"
greet("Ada", "Welcome")
greet(name="Ada", greeting="Hi") # by name, any order
# Several values back
def stats(nums):
return min(nums), max(nums)
low, high = stats([4, 7, 2])
# Defaults that are lists are shared between calls - use None
def add(item, items=None):
if items is None:
items = []
items.append(item)
return items
09 Input and output
input() always returns a string. Wrap it in int() or float() before doing arithmetic.
name = input("Your name? ")
age = int(input("Your age? "))
price = float(input("Price? "))
print("a", "b") # a b
print("a", "b", sep="-") # a-b
print("no newline", end="")
print(f"{name} is {age}")
10 Errors
Catch the specific error you expect. A bare except: hides your own typos.
try:
age = int(input("Age? "))
except ValueError:
print("Not a number")
age = 0
try:
risky()
except (ValueError, KeyError) as err:
print(f"Failed: {err}")
finally:
print("runs either way")
raise ValueError("that will not do")
11 Files and imports
with closes the file for you, even if something goes wrong inside.
with open("plants.txt") as f:
text = f.read() # the whole thing
with open("plants.txt") as f:
for line in f: # a line at a time
print(line.strip())
with open("out.txt", "w") as f: # "w" overwrites, "a" appends
f.write("hello\n")
import random
from math import sqrt, pi
import datetime as dt
random.randint(1, 6)
random.choice(plants)
round(3.14159, 2)
abs(-5)
Nothing on this page mentions that. Try a shorter word, or clear the filter.