← Python Crash Course

Quick reference

Python Cheat Sheet

The syntax you'll reach for most often, in one page — jump to a section below or just scroll through.

Variables & Types

Assigning variables

name = "Ada"
age = 34
height = 1.7
is_student = False

Checking a type

type(age)        # <class 'int'>
isinstance(age, int)   # True

Converting types

A non-empty string, non-zero number, or non-empty container is truthy.

int("42")        # 42
float("3.14")    # 3.14
str(42)          # "42"
bool(0)          # False

Multiple assignment

x, y, z = 1, 2, 3
a = b = 0

Operators

Arithmetic

7 + 3   # 10
7 - 3   # 4
7 * 3   # 21
7 / 3   # 2.333...
7 // 3  # 2   (floor division)
7 % 3   # 1   (remainder)
7 ** 3  # 343 (power)

Comparison

5 == 5   # True
5 != 4   # True
5 > 4    # True
5 <= 5   # True

Logical

True and False   # False
True or False    # True
not True         # False

Shorthand assignment

total = 0
total += 5   # total = total + 5
total -= 2
total *= 3

Strings

f-strings (formatting)

The go-to way to build strings from variables — readable and fast.

name = "Ada"
score = 91.5
f"{name} scored {score:.1f}%"
# "Ada scored 91.5%"

Slicing

s = "Hello, World"
s[0]       # "H"
s[-1]      # "d"
s[0:5]     # "Hello"
s[7:]      # "World"
s[::-1]    # "dlroW ,olleH"

Common methods

s = "  Hello  "
s.strip()        # "Hello"
s.lower()        # "  hello  "
s.upper()        # "  HELLO  "
s.replace("l", "L")
"a,b,c".split(",")   # ['a', 'b', 'c']
"-".join(["a", "b"]) # "a-b"

Checking contents

"lo" in "Hello"      # True
"Hello".startswith("He")  # True
"42".isdigit()       # True

Lists

Creating & indexing

nums = [3, 1, 4, 1, 5]
nums[0]      # 3
nums[-1]     # 5
nums[1:3]    # [1, 4]

Adding & removing

nums.append(9)       # add to the end
nums.insert(0, 100)  # add at index 0
nums.remove(1)       # remove first 1
nums.pop()           # remove & return last item

Sorting

nums.sort()               # in place, ascending
nums.sort(reverse=True)   # in place, descending
sorted(nums)              # new sorted list

List comprehension

A compact way to build a list from a loop plus an optional condition.

squares = [n**2 for n in range(5)]
# [0, 1, 4, 9, 16]
evens = [n for n in range(10) if n % 2 == 0]

Tuples, Dictionaries & Sets

Tuples — fixed, ordered

Like a list, but immutable — can’t be changed after creation.

point = (3, 4)
x, y = point   # unpacking
point[0]       # 3

Dictionaries — key/value pairs

student = {"name": "Ada", "grade": "A"}
student["grade"]          # "A"
student["age"] = 34       # add a key
student.get("age", 0)     # safe lookup, default 0

Looping over a dictionary

for key, value in student.items():
    print(key, "->", value)

Sets — unique, unordered

colors = {"red", "green", "red"}
# {"red", "green"}
colors.add("blue")
{1, 2, 3} & {2, 3, 4}   # {2, 3} intersection

Control Flow & Loops

if / elif / else

if score >= 80:
    grade = "A"
elif score >= 60:
    grade = "B"
else:
    grade = "C"

for loop

for n in range(5):       # 0, 1, 2, 3, 4
    print(n)

for item in ["a", "b"]:
    print(item)

while loop

count = 0
while count < 3:
    print(count)
    count += 1

break, continue, enumerate

for i, item in enumerate(["a", "b", "c"]):
    if item == "b":
        continue
    if i == 2:
        break
    print(i, item)

Functions

Defining & calling

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

greet("Ada")   # "Hello, Ada!"

Default & keyword arguments

def power(base, exponent=2):
    return base ** exponent

power(3)             # 9
power(3, exponent=3) # 27

Variable number of arguments

def total(*numbers):
    return sum(numbers)

total(1, 2, 3)   # 6

lambda (one-line function)

square = lambda n: n ** 2
square(5)   # 25

Handling Errors

try / except

try:
    number = int(input("Enter a number: "))
except ValueError:
    print("That wasn't a number.")

else / finally

"else" runs only if no error happened; "finally" always runs.

try:
    result = 10 / divisor
except ZeroDivisionError:
    print("Can't divide by zero!")
else:
    print("Result:", result)
finally:
    print("Done.")

Raising your own error

def set_age(age):
    if age < 0:
        raise ValueError("Age can't be negative")
    return age

Classes (Basic OOP)

Defining a class

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def describe(self):
        return f"{self.name}: Grade {self.grade}"

Using it

__init__ runs automatically when you create a new Student(...).

s = Student("Ada", "A")
s.name          # "Ada"
s.describe()    # "Ada: Grade A"

Files & Modules

Reading a file

"with" closes the file automatically, even if something goes wrong.

with open("notes.txt") as f:
    text = f.read()

Writing a file

with open("notes.txt", "w") as f:
    f.write("Hello, file!")

Importing a module

import math
math.sqrt(16)     # 4.0

from random import randint
randint(1, 6)     # a random int 1–6

Handy Built-ins

len, range, sum, min, max

len([1, 2, 3])          # 3
list(range(2, 10, 2))   # [2, 4, 6, 8]
sum([1, 2, 3])          # 6
min(4, 1, 7)             # 1
max([4, 1, 7])           # 7

zip — pair up two lists

names = ["Ada", "Grace"]
scores = [91, 88]
list(zip(names, scores))
# [('Ada', 91), ('Grace', 88)]

map & filter

list(map(str.upper, ["a", "b"]))
# ['A', 'B']
list(filter(lambda n: n > 2, [1, 2, 3, 4]))
# [3, 4]