Variables & Types
name = "Ada" # str — text
age = 12 # int — whole number
height = 1.52 # float — decimal
is_coder = True # bool — True / False
print(type(age)) # <class 'int'>
age_text = str(age) # convert to text: "12"
number = int("42") # convert to number: 42
Strings
greeting = f"Hello {name}, you are {age}!" # f-strings — use these
shout = greeting.upper() # "HELLO ADA..."
first = name[0] # "A" (counting starts at 0!)
pieces = "a,b,c".split(",") # ["a", "b", "c"]
"ada" in name.lower() # True — check if text contains text
" spaced out ".strip() # "spaced out" — trims outer whitespace
"a-b-c".replace("-", "_") # "a_b_c"
", ".join(["a", "b", "c"]) # "a, b, c" — opposite of split()
| Method | What it does | Example |
|---|---|---|
| .strip() | Removes leading/trailing whitespace | " hi ".strip() → "hi" |
| .split() | Breaks text into a list | "a,b".split(",") → ["a","b"] |
| .join() | Combines a list into text | "-".join(["a","b"]) → "a-b" |
| .replace() | Swaps one substring for another | "hi".replace("h","b") → "bi" |
| .find() | Returns index of first match, or -1 | "hello".find("l") → 2 |
Lists & Dictionaries
scores = [90, 85, 77]
scores.append(100) # add to the end
scores[0] # 90 — first item
len(scores) # 4
scores.sort(reverse=True) # biggest first
player = {"name": "Ada", "level": 3}
player["level"] += 1 # level up!
player.get("coins", 0) # 0 — safe lookup with a default
for key, value in player.items(): # loop over both keys and values
print(key, "->", value)
players = {"ada": {"level": 3}, "sam": {"level": 5}} # dict of dicts
players["ada"]["level"] # 3 — nested access
Use .get(key, default) instead of player["coins"] whenever a key might not exist — a plain lookup raises a KeyError and crashes the program, while .get() quietly returns the default you supply. Nested dictionaries (a dict whose values are themselves dicts) are the most common way to represent structured records, like a small database of players, before you reach for an actual database.
If / Elif / Else
if age >= 13:
print("Teen coder")
elif age >= 7:
print("Junior coder")
else:
print("Future coder")
# combine checks
if age > 7 and is_coder:
print("Ready for projects!")
Loops
for score in scores: # loop a list
print(score)
for i in range(5): # 0,1,2,3,4
print(f"lap {i}")
count = 3
while count > 0: # loop until condition fails
print(count)
count -= 1 # never forget this line!
for i, score in enumerate(scores): # get index AND value together
if score < 50:
continue # skip to the next item
if score == 100:
break # stop the loop entirely
print(f"#{i}: {score}")
continue skips the rest of the current loop iteration and moves on to the next one; break exits the loop immediately, even if there were more items left. enumerate() is the idiomatic way to get both the index and the value while looping — reaching for a manual counter variable instead is a common sign you can simplify the loop.
If your program freezes, you probably wrote a while loop where the condition never becomes False. Press Ctrl+C to stop it, then make sure something inside the loop changes the variable being tested.
Functions
def greet(name, excited=False):
"""Say hello, optionally with energy."""
if excited:
return f"HELLO {name.upper()}!!!"
return f"Hello {name}."
print(greet("Ada")) # Hello Ada.
print(greet("Ada", excited=True)) # HELLO ADA!!!
def total(*numbers, **labels):
"""*args collects extra positional args into a tuple,
**kwargs collects extra keyword args into a dict."""
print(numbers, labels)
total(1, 2, 3, unit="points") # (1, 2, 3) {'unit': 'points'}
double = lambda n: n * 2 # a tiny one-line function
print(double(5)) # 10
Default arguments (like excited=False above) let a function be called with fewer arguments most of the time. *args and **kwargs let a function accept an unknown number of extra values — useful once you start writing functions that wrap or forward calls to other functions. A lambda is a small anonymous function, handy for one-off logic passed into sorted(), map(), or filter().
Sets & Tuples
Lists aren't the only way to group values. A tuple locks data so it can't change by accident, and a set exists to do one job well: guarantee every item is unique.
# tuple — like a list, but immutable (can't change after creation)
point = (10, 20)
x, y = point # unpacking: x=10, y=20
# set — unordered, duplicates are removed automatically
tags = {"python", "beginner", "python"}
print(tags) # {'python', 'beginner'} — only 2 items
tags.add("2026")
print("python" in tags) # True — membership checks are very fast
Use a tuple when the data shouldn't change — coordinates, an RGB colour, a function returning more than one value. Use a set when you only care about uniqueness and don't need an order, such as removing duplicates from a list with list(set(my_list)).
| Type | Ordered? | Changeable? | Duplicates? | Written as |
|---|---|---|---|---|
| List | Yes | Yes | Allowed | [1, 2, 3] |
| Tuple | Yes | No | Allowed | (1, 2, 3) |
| Set | No | Yes (add/remove) | Not allowed | {1, 2, 3} |
| Dictionary | Insertion order | Yes | Keys must be unique | {"a": 1} |
List Comprehensions
A comprehension builds a new list, dict, or set in a single readable line, instead of writing an empty container and appending to it inside a loop.
squares = [n * n for n in range(10)] # [0, 1, 4, 9, ...]
evens = [n for n in range(20) if n % 2 == 0] # filter while building
names_upper = [name.upper() for name in ["ada", "sam"]]
# the dictionary version works the same way
lengths = {name: len(name) for name in ["ada", "sam", "zoe"]}
If you find yourself writing result = [] then for x in y: result.append(...), that pattern is almost always a comprehension in disguise — and the comprehension version is usually faster too.
Exception Handling: try / except / finally
Programs meet bad input, missing files, and unreachable servers constantly. Exception handling lets you catch those problems and respond, instead of letting the whole program crash.
try:
age = int(input("Enter your age: "))
result = 100 / age
except ValueError:
print("That's not a number.")
except ZeroDivisionError:
print("Age can't be zero.")
else:
print(f"100 divided by your age is {result}")
finally:
print("Done checking age.") # always runs, error or not
The Exception Handling Golden Rule
- Only catch the specific errors you expect — never a bare
except: elseruns only if no exception was raised in thetryblockfinallyalways runs — use it for cleanup, like closing a file or connection- An uncaught exception crashing your program is often better than silently hiding a real bug
Reading & Writing Files
Most real programs need to persist data somewhere. The built-in open() function handles reading and writing plain text files.
with open("scores.txt", "w") as f:
f.write("90\n85\n77\n")
with open("scores.txt", "r") as f:
lines = f.readlines() # list of lines, each ending in \n
for line in lines:
print(line.strip()) # strip() removes the trailing \n
Opening a file with with open(...) as f: automatically closes it when the block ends, even if an error happens inside. Opening a file without with and forgetting f.close() is a common source of "file in use" and data-loss bugs.
Classes & Objects: Python OOP Basics
A class is a blueprint for creating objects that bundle data (attributes) with the actions that belong to that data (methods).
class Player:
def __init__(self, name, level=1):
self.name = name
self.level = level
def level_up(self):
self.level += 1
return f"{self.name} is now level {self.level}!"
ada = Player("Ada")
print(ada.level_up()) # Ada is now level 2!
print(ada.name, ada.level) # Ada 2
__init__ runs automatically when a new object is created and sets up its starting attributes. self refers to the specific object the method was called on — it's how ada.level_up() knows to change Ada's level and not some other player's.
Modules, Imports & Installing Packages
Python's standard library ships with dozens of ready-made modules, and the wider Python ecosystem adds thousands more through pip, Python's package installer.
import math
from random import randint
import numpy as np # after running: pip install numpy
print(math.sqrt(16)) # 4.0
print(randint(1, 6)) # random number from 1 to 6
Install Python
Download the latest Python 3 release from python.org, or use your OS package manager. Check the box that adds Python to your PATH during install.
Verify the install
Open a terminal and run python --version (or python3 --version). You should see a version number like 3.12.x.
Create a virtual environment
Run python -m venv env inside your project folder. This keeps each project's packages separate so they never conflict with each other.
Activate it
On Windows: env\Scripts\activate. On macOS/Linux: source env/bin/activate. Your terminal prompt will show the environment name when it's active.
Install and run
Use pip install package-name to add a library, then run your script with python your_file.py.
The 5 Errors Every Beginner Meets
| Error | What it means | Usual fix |
|---|---|---|
| SyntaxError | Python can't read the line | Missing : after if/for/def, or unclosed quote/bracket |
| IndentationError | Spacing is wrong | Indent blocks with exactly 4 spaces, consistently |
| NameError | Using a name that doesn't exist | Typo, or you used a variable before creating it |
| TypeError | Mixing incompatible types | "age: " + str(12) — convert numbers before joining to text |
| IndexError | Asking for a list item that isn't there | Remember lists start at 0; last item is len(x)-1 |
Python error messages put the most useful line last. Read the final line first, then the line number it points to. 90% of beginner bugs are solved this way.
Common Built-in Functions
Python comes with dozens of functions ready to use without any import. These are the ones you'll reach for constantly as a beginner.
| Function | What it does | Example |
|---|---|---|
| len() | Counts items in a list, string, or dict | len([1,2,3]) → 3 |
| range() | Generates a sequence of numbers | range(5) → 0,1,2,3,4 |
| type() | Shows a value's data type | type(3.5) → float |
| sorted() | Returns a new sorted list | sorted([3,1,2]) → [1,2,3] |
| enumerate() | Pairs each item with its index | for i, v in enumerate(x) |
| zip() | Combines two sequences pairwise | zip(names, scores) |
| map() | Applies a function to every item | map(str, [1,2,3]) |
| input() | Reads a line of text the user types | input("Name: ") |
Common Beginner Mistakes
Most beginner bugs come from a handful of repeat offenders. Recognising them on sight saves hours of confused debugging.
- Using
=(assignment) where you meant==(comparison) - Forgetting the colon
:afterif/for/def/while - Mixing tabs and spaces for indentation in the same file
- Adding or removing items from a list while looping over it
- Using a mutable default argument like
def f(items=[]) - Forgetting that text and numbers don't auto-combine — convert with
str()first
Frequently Asked Questions
Do I need to memorize all of this?
No — that's the point of a cheat sheet. Bookmark it and look things up while you build. Fluency comes from writing code repeatedly, not from memorizing syntax up front.
Should I learn Python 2 or Python 3?
Python 3 — this cheat sheet uses Python 3.12+ syntax throughout. Python 2 reached its official end of life years ago and shouldn't be used for anything new.
What's the difference between a list and a NumPy array?
Python's built-in list is flexible and can hold mixed types. A NumPy array (from the numpy library) is faster for numeric work but must hold a single data type throughout. Start with list; reach for NumPy once you're doing heavier numeric or data work.
How do I know when to write a function vs. a class?
Reach for a function when you're performing a single action on some data. Reach for a class when you're modelling a "thing" that has both data (attributes) and behaviour (methods) that belong together — like the Player example above, which bundles a name and level with the action of levelling up.
· · ·
Where to Go Next
A cheat sheet shows you the vocabulary — projects teach you the language. Pick a mini-project and build it with this page open beside you. A good first project touches several of the sections above at once: a simple to-do list app uses lists, dictionaries, loops, and functions; a number-guessing game uses conditions, loops, and exception handling for bad input; a text-based inventory system uses classes, files, and dictionaries together.
Don't try to master every section before you start building — that's backwards. Pick the smallest project that sounds fun, write the first function, and come back to this page whenever you forget a piece of syntax. That loop — build, get stuck, look it up, keep building — is how every working developer actually learns, cheat sheet or not.
The Essential Points
- f-strings, lists, dicts, for-loops and functions cover 90% of beginner Python
- Counting starts at 0 — half of all beginner bugs come from forgetting this
- Read error messages from the bottom line up
- Learn by building: our free Python course turns each of these patterns into a project
- More references on the cheat sheet hub — SQL, Git, HTML and more