Python Cheat Sheet

Core Python syntax, control flow, operators, collections, and everyday language patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Basics and running code
Multiple assignment
x, y = 10, 20

# Multiple assignment

Swap variables
a, b = b, a

# Swap variables

Read input
name = input("Name: ")

# Read input

Command-line one-liner
python -c "print(sum(range(10)))"

# Command-line one-liner

Run a module
python -m http.server 8000

# Run a module

## Numbers, booleans, and comparisons
Integer division
quotient = 7 // 3

# Integer division

Modulo
remainder = 7 % 3

# Modulo

Exponentiation
power = 2 ** 8

# Exponentiation

Chained comparison
is_between = 1 < x < 10

# Chained comparison

Truthy fallback
username = supplied_name or "anonymous"

# Truthy fallback

Ternary expression
label = "adult" if age >= 18 else "minor"

# Ternary expression

## Conditionals and loops
If / elif / else
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

# If / elif / else

For over a list
for name in names:
    print(name)

# For over a list

For with enumerate
for idx, value in enumerate(items, start=1):
    print(idx, value)

# For with enumerate

For with zip
for name, score in zip(names, scores):
    print(name, score)

# For with zip

While loop
while queue:
    item = queue.pop(0)
    print(item)

# While loop

Loop with else
for item in items:
    if item == target:
        print("found")
        break
else:
    print("not found")

# Loop with else

Match statement
match status:
    case 200:
        message = "ok"
    case 404:
        message = "not found"
    case _:
        message = "other"

# Match statement

## Collections overview
List literal
items = [1, 2, 3]

# List literal

Tuple literal
point = (10, 20)

# Tuple literal

Set literal
tags = {"python", "api", "cli"}

# Set literal

Dictionary literal
user = {"id": 1, "name": "Ada"}

# Dictionary literal

Membership test
if "python" in tags:
    print("present")

# Membership test

Destructuring assignment
first, *middle, last = values

# Destructuring assignment