Python Cheatsheet

View saved

Use this sheet when you need a fast reminder of everyday Python patterns. Each entry pairs a short definition with a small example you can adapt.

For step-by-step lessons, follow the related Python tutorials linked below.

Syntax basics

print()

Writes values to standard output. Separate arguments with commas; they print with spaces by default.

print("Hello", 42)
print("a", "b", sep="-")

Variables

Names bound to values. No type declaration; reassignment is allowed. Prefer snake_case for locals.

name = "Ada"
count = 3
count = count + 1

Comments

Everything after # on a line is ignored. Use comments to explain why, not to restate the code.

# Convert Celsius to Fahrenheit
temp_f = temp_c * 9 / 5 + 32

f-strings

Format strings by embedding expressions in curly braces. Available in Python 3.6+.

user = "Sam"
print(f"Welcome, {user}!")
print(f"{2 + 2 = }")

input()

Reads a line from the user as a string. Convert with int() or float() when you need a number.

age = int(input("Age: "))
print(age + 1)

Types & collections

int / float / str / bool

Core scalar types. bool is a subclass of int; True and False are the only boolean values.

n = 10
x = 3.14
s = "hi"
ok = True

list

Ordered, mutable sequence. Index from 0; negative indices count from the end.

nums = [3, 1, 4]
nums.append(1)
print(nums[0], nums[-1])

tuple

Ordered, immutable sequence. Useful for fixed pairs and multiple return values.

point = (10, 20)
x, y = point

dict

Unordered (insertion-ordered) key→value map. Keys must be hashable; values can be any type.

user = {"name": "Lee", "age": 20}
print(user["name"])
user["age"] = 21

set

Unordered collection of unique items. Fast membership tests and set algebra.

tags = {"python", "cli"}
tags.add("python")  # no change
print("cli" in tags)

len / indexing / slicing

len() works on sequences and mappings. Slices use start:stop:step and do not include stop.

s = "abcdef"
print(len(s), s[1:4], s[::-1])

Control flow

if / elif / else

Branch on conditions. Only the first true branch runs. Indentation defines the block.

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

for loops

Iterate over any iterable. range(n) yields 0..n-1; range(a, b) yields a..b-1.

for i in range(3):
    print(i)
for ch in "hi":
    print(ch)

while loops

Repeat while a condition stays true. Ensure the loop body eventually makes the condition false.

n = 3
while n > 0:
    print(n)
    n -= 1

break / continue

break exits the nearest loop early. continue skips the rest of the current iteration.

for n in range(10):
    if n % 2:
        continue
    if n > 6:
        break
    print(n)

comprehensions

Build a list, set, or dict in one expression. Prefer them for simple transforms; use loops when logic grows.

squares = [n * n for n in range(5)]
evens = {n for n in range(10) if n % 2 == 0}

Functions

def

Defines a named function. Parameters are local; return sends a value back to the caller.

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

print(greet("Maya"))

Default & keyword args

Defaults fill missing positional args. Callers can pass arguments by name in any order.

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

print(power(3), power(exp=3, base=2))

*args / **kwargs

Collect extra positional args into a tuple and extra keyword args into a dict.

def show(*args, **kwargs):
    print(args, kwargs)

show(1, 2, a=3)

lambda

Small anonymous function of one expression. Handy for key= callbacks; avoid complex lambdas.

pairs = [(2, "b"), (1, "a")]
pairs.sort(key=lambda p: p[0])

scope (LEGB)

Names resolve Local → Enclosing → Global → Built-in. Use global/nonlocal only when you must rebind outer names.

x = 1

def outer():
    x = 2
    def inner():
        return x
    return inner()

print(outer())  # 2

Files & modules

open / read / write

Prefer a with block so files close automatically. Modes include 'r', 'w', 'a', and 'rb'/'wb'.

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

with open("notes.txt", encoding="utf-8") as f:
    print(f.read())

pathlib

Object-oriented paths. Join with /, check existence, and read/write text without manual open in many cases.

from pathlib import Path
p = Path("data") / "log.txt"
p.parent.mkdir(exist_ok=True)
p.write_text("ok", encoding="utf-8")

import

Load a module or selected names. Prefer import module for clarity; from module import name for frequent helpers.

import math
from math import sqrt
print(math.pi, sqrt(9))

if __name__ == '__main__'

True only when the file is run as a script, not when imported. Put CLI entry points here.

def main():
    print("run")

if __name__ == "__main__":
    main()

pip / venv

Create an isolated environment, then install packages into it so projects do not share global site-packages.

python3 -m venv .venv
source .venv/bin/activate  # Windows: .venv\Scripts\activate
pip install requests

Errors

try / except

Catch expected exceptions so the program can recover or report a clear message.

try:
    n = int("x")
except ValueError as e:
    print("bad number:", e)

else / finally

else runs when no exception occurred. finally always runs for cleanup.

try:
    f = open("a.txt")
except OSError:
    print("missing")
else:
    data = f.read()
    f.close()
finally:
    print("done")

raise

Signal an error yourself. Prefer built-in exception types with a clear message.

def positive(n):
    if n <= 0:
        raise ValueError("n must be > 0")
    return n

Common exceptions

TypeError, ValueError, KeyError, IndexError, AttributeError, and FileNotFoundError cover most beginner mistakes.

d = {"a": 1}
# KeyError: d["b"]
# IndexError: [1, 2][5]
# FileNotFoundError: open("nope.txt")

Comments

One comment per signed-in account. Comments are saved with this page’s URL.