// python · reference

Python Cheat Sheet for Beginners: Syntax at a Glance

A one-page Python reference for beginners. Variables, strings, lists, dictionaries, loops, functions, files, errors and classes, each with a short example and a link to the full guide.

Keep this page open while you practise. Each section gives the syntax you’ll reach for most often, with a link to the full guide if you need more explanation. Bookmark it with Ctrl + D (Cmd + D on a Mac).

Output, input and comments

python
print("Hello")                  # show text
print("a", "b", sep="-")        # a-b
name = input("Name? ")          # input() always returns a string
age = int(input("Age? "))       # convert to a number
# a comment: Python ignores everything after the #

Full guide: Your First Python Program

Variables and types

python
count = 10          # int
price = 4.99        # float
name = "Ava"        # str
is_ready = True     # bool
nothing = None      # no value

type(price)         # <class 'float'>
int("42")           # 42
float("3.5")        # 3.5
str(99)             # "99"

Full guide: Variables and Data Types

Operators

python
7 + 2    # 9      7 - 2    # 5      7 * 2    # 14
7 / 2    # 3.5    7 // 2   # 3      7 % 2    # 1
7 ** 2   # 49     round(3.14159, 2)   # 3.14

x += 1             # x = x + 1
# comparisons give True or False:  ==  !=  <  >  <=  >=
# combine conditions:              and  or  not
5 > 3 and 2 == 2   # True

Full guide: Operators and Maths

Strings

python
s = "CodeRunner"
len(s)              # 10
s[0]                # 'C'
s[-1]               # 'r'
s[0:4]              # 'Code'
s.lower()           # 'coderunner'
s.upper()           # 'CODERUNNER'
" hi ".strip()      # 'hi'
s.replace("Code", "Fun")   # 'FunRunner'
"a,b,c".split(",")  # ['a', 'b', 'c']
"-".join(["a", "b"])       # 'a-b'
"Run" in s          # True
f"{name} is {age}"  # f-string
f"{price:.2f}"      # 2 decimal places

Full guide: Working with Strings

Conditions

python
if score >= 80:
    print("A")
elif score >= 60:
    print("B")
else:
    print("Keep going")

grade = "pass" if score >= 50 else "fail"   # one-line if

Loops

python
for i in range(5):          # 0 1 2 3 4
    print(i)

for i in range(1, 11, 2):   # 1 3 5 7 9 (start, stop, step)
    print(i)

for item in my_list:
    print(item)

for i, item in enumerate(my_list, start=1):
    print(i, item)

while count > 0:
    count -= 1

# inside a loop:
#   break     leave the loop
#   continue  skip to the next pass

Full guide: If Statements and Loops

Lists

python
nums = [3, 1, 2]
nums.append(4)        # [3, 1, 2, 4]
nums.insert(0, 9)     # [9, 3, 1, 2, 4]
nums.remove(9)        # removes the first 9
last = nums.pop()     # removes and returns the last item
nums.sort()           # sorts in place
sorted(nums)          # returns a new sorted list
len(nums), sum(nums), min(nums), max(nums)
copy = nums.copy()    # a real copy (not copy = nums)
squares = [n * n for n in nums]   # list comprehension

Full guide: Python Lists

Tuples and sets

python
point = (3, 5)        # tuple: can't be changed
x, y = point          # unpacking
single = (5,)         # one-item tuple needs a comma

s = {1, 2, 2, 3}      # set: {1, 2, 3}, no duplicates
s.add(4)
empty = set()         # not {} (that's a dictionary)
# a & b   both     a | b   either     a - b   only in a

Full guide: Tuples and Sets

Dictionaries

python
ages = {"Ava": 15, "Leo": 17}
ages["Mia"] = 16          # add or update
ages["Ava"]               # 15
ages.get("Sam", 0)        # 0 (no KeyError)
"Leo" in ages             # True
del ages["Leo"]

for name, age in ages.items():
    print(name, age)

counts[w] = counts.get(w, 0) + 1   # counting pattern

Full guide: Python Dictionaries

Functions

python
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet("Ava")              # 'Hello, Ava!'
greet("Leo", "Hi")        # 'Hi, Leo!'

def min_max(nums):
    return min(nums), max(nums)   # returns a tuple

low, high = min_max([4, 9, 1])

Full guide: Python Functions

Errors and exceptions

python
try:
    n = int(input("Number: "))
except ValueError:
    print("That wasn't a number")
else:
    print("You typed", n)
finally:
    print("Done")

raise ValueError("Bad value")    # raise your own error
Error Usual cause
SyntaxError missing bracket, quote or colon
IndentationError spaces at the start of a line are wrong
NameError misspelt or undefined name
TypeError wrong type, e.g. "5" + 3
ValueError right type, bad value, e.g. int("abc")
IndexError list position doesn’t exist
KeyError dictionary key doesn’t exist

Full guides: Reading Error Messages · try and except

Files and CSV

python
with open("notes.txt", "w", encoding="utf-8") as f:   # "w" overwrites
    f.write("Hello\n")

with open("notes.txt", "a", encoding="utf-8") as f:   # "a" appends
    f.write("Another line\n")

with open("notes.txt", encoding="utf-8") as f:        # read
    for line in f:
        print(line.strip())

import csv
with open("data.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"])

Full guides: Reading and Writing Files · CSV Files

Modules

python
import random
random.randint(1, 6)          # 1 to 6 inclusive
random.choice(["a", "b"])
random.shuffle(my_list)

import math
math.sqrt(16)       # 4.0
math.ceil(4.2)      # 5
math.floor(4.7)     # 4
math.pi             # 3.141592653589793

from datetime import date
date.today()
terminal
python -m pip install package-name     # install a package
python -m venv .venv                    # make a virtual environment

Full guide: Modules and pip

Classes

python
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return f"{self.name} says woof"

    def __str__(self):
        return f"Dog called {self.name}"

class Puppy(Dog):                 # inheritance
    def bark(self):
        return f"{self.name} says yip"

rex = Dog("Rex")
print(rex.bark())                 # Rex says woof
print(Puppy("Bo").bark())         # Bo says yip

Full guide: Classes and Objects

Useful built-in functions

Function Example Result
len() len([1, 2, 3]) 3
range() list(range(3)) [0, 1, 2]
sum() / min() / max() max([4, 9, 2]) 9
sorted() sorted([3, 1, 2]) [1, 2, 3]
abs() abs(-5) 5
round() round(2.567, 1) 2.6
enumerate() list(enumerate("ab")) [(0, 'a'), (1, 'b')]
zip() list(zip("ab", [1, 2])) [('a', 1), ('b', 2)]
isinstance() isinstance(5, int) True
help() help(str.split) shows documentation

Test what you remember in PyQuest, or look up any unfamiliar word in the Programming Glossary.