x = 5 items = [1, 2, 3] for i in items: print(i) def greet(name): Every basic. One page.
Programming
Programming · Python

Python Cheat Sheet for Beginners: Every Basic You Need on One Page

Variables, strings, lists, loops, functions and the 5 errors every beginner hits — with copy-ready examples.

Bookmark this page. It's the reference we wish existed when we started: every core Python pattern a beginner needs, in runnable snippets, with plain-English notes. Working through our free Python course? This is your companion sheet.

Pillar 1
Data & Types
str · int · list
What your code holds
Variables, strings, lists, dicts, tuples and sets — the containers every program is built from.
Pillar 2
Control Flow
if · for · while
Decisions & repetition
Conditions and loops decide what runs, when, and how many times.
Pillar 3
Functions & Classes
def · class
Reusable logic
Package logic once, reuse it everywhere — from a single function to a full class.
Pillar 4
Errors & Debugging
try · except
When things break
Reading errors and handling exceptions turns crashes into controlled, recoverable moments.

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()
MethodWhat it doesExample
.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.

⚠️ Infinite loop alert

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)).

TypeOrdered?Changeable?Duplicates?Written as
ListYesYesAllowed[1, 2, 3]
TupleYesNoAllowed(1, 2, 3)
SetNoYes (add/remove)Not allowed{1, 2, 3}
DictionaryInsertion orderYesKeys 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"]}
💡 When to reach for one

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:
  • else runs only if no exception was raised in the try block
  • finally always 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
⚠️ Always use `with`

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
1

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.

2

Verify the install

Open a terminal and run python --version (or python3 --version). You should see a version number like 3.12.x.

3

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.

4

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.

5

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

ErrorWhat it meansUsual fix
SyntaxErrorPython can't read the lineMissing : after if/for/def, or unclosed quote/bracket
IndentationErrorSpacing is wrongIndent blocks with exactly 4 spaces, consistently
NameErrorUsing a name that doesn't existTypo, or you used a variable before creating it
TypeErrorMixing incompatible types"age: " + str(12) — convert numbers before joining to text
IndexErrorAsking for a list item that isn't thereRemember lists start at 0; last item is len(x)-1
💡 Read errors bottom-up

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.

FunctionWhat it doesExample
len()Counts items in a list, string, or dictlen([1,2,3]) → 3
range()Generates a sequence of numbersrange(5) → 0,1,2,3,4
type()Shows a value's data typetype(3.5) → float
sorted()Returns a new sorted listsorted([3,1,2]) → [1,2,3]
enumerate()Pairs each item with its indexfor i, v in enumerate(x)
zip()Combines two sequences pairwisezip(names, scores)
map()Applies a function to every itemmap(str, [1,2,3])
input()Reads a line of text the user typesinput("Name: ")

Common Beginner Mistakes

Most beginner bugs come from a handful of repeat offenders. Recognising them on sight saves hours of confused debugging.

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
IA
Irfana Aslam
Founder · AI Researcher · Full-Stack Developer, BitWithBite
Advancing science through Artificial Intelligence, Computer Vision, and impactful technology solutions. Irfana built BitWithBite from scratch to make world-class tech education accessible to every learner worldwide.