Python Cheat Sheet

Use this Python cheat sheet as a quick reference for syntax, variables, data types, conditionals, loops, functions, collections, files, errors, modules, classes, virtual environments, and common patterns.

Basic Python Syntax

Python uses indentation to group code.

message = "Hello, Python"
print(message)

Syntax Basics

  • Use indentation instead of curly braces.
  • Use # for single-line comments.
  • Use meaningful variable names.
  • Python is case-sensitive, so name and Name are different variables.
  • Most Python files use the .py extension.

Run Python Code

Run a Python File

python app.py

On some systems, use:

python3 app.py

Check Python Version

python --version

Or:

python3 --version

Open the Python Shell

python

Exit the shell:

exit()

Comments

Single-Line Comment

# This is a comment

Inline Comment

total = 100  # Starting balance

Multi-Line String Used as a Note

"""
This text can span multiple lines.
Use real comments for normal code notes.
"""

Use comments to explain why something happens, not every obvious line.

Variables

Create Variables

name = "Alex"
age = 28
is_active = True

Reassign Variables

score = 10
score = 15

Multiple Assignment

x, y, z = 1, 2, 3

Same Value for Multiple Variables

a = b = c = 0

Naming Rules

  • Use letters, numbers, and underscores.
  • Do not start variable names with numbers.
  • Use snake_case for normal variable names.
  • Avoid names that shadow built-ins, such as list, str, or sum.

Data Types

String

name = "Alex"

Integer

age = 28

Float

price = 19.99

Boolean

is_logged_in = True
has_access = False

None

selected_user = None

List

languages = ["Python", "JavaScript", "SQL"]

Tuple

point = (10, 20)

Dictionary

user = {
    "name": "Alex",
    "age": 28
}

Set

unique_tags = {"python", "web", "data"}

Check Types

Use type()

value = 42
print(type(value))

Use isinstance()

age = 28

if isinstance(age, int):
    print("Age is an integer")

isinstance() works well when you need to check a value before using it.

Type Conversion

Convert to String

age = 28
text = str(age)

Convert to Integer

value = "42"
number = int(value)

Convert to Float

price = "19.99"
price_number = float(price)

Convert to Boolean

is_valid = bool("hello")

Convert to List

letters = list("abc")
print(letters)

Strings

Create Strings

single = 'Hello'
double = "Hello"

Multiline String

message = """
Line one
Line two
"""

f-String

name = "Alex"
message = f"Hello, {name}"
print(message)

String Length

text = "Python"
print(len(text))

Change Case

text = "Python"

print(text.lower())
print(text.upper())
print(text.title())

Remove Whitespace

text = "  hello  "
print(text.strip())

Check Text

title = "Learn Python"

print("Python" in title)
print(title.startswith("Learn"))
print(title.endswith("Python"))

Replace Text

text = "I like Java"
new_text = text.replace("Java", "Python")

print(new_text)

Split and Join

tags = "python,css,html"
tag_list = tags.split(",")

print(tag_list)
words = ["Learn", "Python"]
sentence = " ".join(words)

print(sentence)

Numbers and Math

Basic Math

a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)

Floor Division

print(10 // 3)

Remainder

print(10 % 3)

Power

print(2 ** 3)

Round

price = 19.987
print(round(price, 2))

Common Math Functions

numbers = [5, 2, 9]

print(min(numbers))
print(max(numbers))
print(sum(numbers))

Operators

Comparison Operators

print(10 == 10)
print(10 != 5)
print(10 > 5)
print(10 >= 10)
print(5 < 10)
print(5 <= 5)

Logical Operators

is_adult = True
has_ticket = False

print(is_adult and has_ticket)
print(is_adult or has_ticket)
print(not is_adult)

Assignment Operators

score = 10

score += 5
score -= 2
score *= 3
score /= 2

Membership Operators

languages = ["Python", "JavaScript"]

print("Python" in languages)
print("Ruby" not in languages)

Conditionals

if

age = 20

if age >= 18:
    print("Adult")

if...else

is_logged_in = False

if is_logged_in:
    print("Welcome back")
else:
    print("Please log in")

elif

score = 85

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("Keep practicing")

Ternary Expression

age = 20
message = "Adult" if age >= 18 else "Minor"

print(message)

Use ternary expressions for short decisions. Use normal if...else blocks for longer logic.

Loops

for Loop

languages = ["Python", "JavaScript", "SQL"]

for language in languages:
    print(language)

range()

for number in range(5):
    print(number)

Start and stop:

for number in range(1, 6):
    print(number)

Step value:

for number in range(0, 10, 2):
    print(number)

while Loop

count = 0

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

break

for number in range(10):
    if number == 5:
        break

    print(number)

continue

for number in range(5):
    if number == 2:
        continue

    print(number)

Loop with Index

names = ["Alex", "Sam", "Taylor"]

for index, name in enumerate(names):
    print(index, name)

Lists

Create a List

fruits = ["apple", "banana", "orange"]

Access Items

print(fruits[0])
print(fruits[-1])

Change an Item

fruits[1] = "mango"

Add Items

fruits.append("grape")
fruits.insert(0, "kiwi")

Remove Items

fruits.remove("apple")
last_fruit = fruits.pop()

List Length

print(len(fruits))

Slice a List

numbers = [1, 2, 3, 4, 5]

print(numbers[1:4])
print(numbers[:3])
print(numbers[3:])

Sort a List

numbers = [3, 1, 4, 2]

numbers.sort()
print(numbers)

Create a sorted copy:

numbers = [3, 1, 4, 2]

sorted_numbers = sorted(numbers)
print(sorted_numbers)

List Comprehensions

List comprehensions create lists in a compact way.

numbers = [1, 2, 3, 4]

squares = [number ** 2 for number in numbers]

print(squares)

With a Condition

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = [number for number in numbers if number % 2 == 0]

print(even_numbers)

Use comprehensions for simple transformations. Use normal loops when logic becomes hard to read.

Tuples

Tuples are ordered and cannot be changed after creation.

point = (10, 20)

print(point[0])
print(point[1])

Unpack a Tuple

x, y = point

print(x)
print(y)

Use tuples for fixed groups of values, such as coordinates or pairs.

Dictionaries

Create a Dictionary

user = {
    "name": "Alex",
    "age": 28,
    "is_member": True
}

Access Values

print(user["name"])

Safer access with get():

print(user.get("email"))
print(user.get("email", "No email"))

Add or Update Values

user["city"] = "Vienna"
user["age"] = 29

Remove Values

user.pop("city")

Loop Through Keys and Values

for key, value in user.items():
    print(key, value)

Dictionary Comprehension

numbers = [1, 2, 3]

squares = {number: number ** 2 for number in numbers}

print(squares)

Sets

Sets store unique values.

tags = {"python", "web", "python"}

print(tags)

Add and Remove

tags.add("data")
tags.remove("web")

Set Operations

a = {"python", "html", "css"}
b = {"python", "sql"}

print(a | b)
print(a & b)
print(a - b)

Set Uses

  • Remove duplicate values.
  • Check membership quickly.
  • Compare groups of values.
  • Find shared or different items.

Functions

Define a Function

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

Call a Function

message = greet("Alex")
print(message)

Default Parameter

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

print(greet())

Keyword Arguments

def create_user(name, age):
    return {
        "name": name,
        "age": age
    }

user = create_user(age=28, name="Alex")
print(user)

Return Multiple Values

def get_coordinates():
    return 10, 20

x, y = get_coordinates()
print(x, y)

Lambda Functions

A lambda is a small anonymous function.

double = lambda number: number * 2

print(double(5))

Use lambda functions for short callbacks.

users = [
    {"name": "Alex", "age": 28},
    {"name": "Sam", "age": 24}
]

users.sort(key=lambda user: user["age"])

print(users)

Use normal functions when the logic needs more than one simple expression.

Scope

Local Scope

def show_message():
    message = "Hello"
    print(message)

show_message()

message only exists inside the function.

Global Scope

count = 0

def show_count():
    print(count)

show_count()

Avoid Unnecessary Globals

def increment(count):
    return count + 1

count = 0
count = increment(count)

print(count)

Passing values into functions is usually clearer than changing global variables.

Files

Read a File

with open("notes.txt", "r", encoding="utf-8") as file:
    content = file.read()

print(content)

Read Lines

with open("notes.txt", "r", encoding="utf-8") as file:
    lines = file.readlines()

print(lines)

Write a File

with open("result.txt", "w", encoding="utf-8") as file:
    file.write("Task complete")

Append to a File

with open("log.txt", "a", encoding="utf-8") as file:
    file.write("New log entry\n")

Use with open(...) so Python closes the file automatically.

Paths

Use pathlib

from pathlib import Path

current_directory = Path.cwd()
file_path = current_directory / "data.txt"

print(file_path)

Get the Script Folder

from pathlib import Path

script_directory = Path(__file__).parent
config_file = script_directory / "config.json"

print(config_file)

Use Path.cwd() for the folder where Python is running. Use Path(__file__).parent for the folder that contains the script.

Error Handling

try...except

try:
    number = int("abc")
except ValueError:
    print("Invalid number")

Catch Multiple Errors

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid value")

else and finally

try:
    number = int("42")
except ValueError:
    print("Invalid number")
else:
    print("Conversion worked")
finally:
    print("Done")

Raise an Error

def divide(a, b):
    if b == 0:
        raise ValueError("b cannot be zero")

    return a / b

Imports and Modules

Import a Module

import math

print(math.sqrt(16))

Import a Specific Function

from math import sqrt

print(sqrt(16))

Import with an Alias

import datetime as dt

today = dt.date.today()
print(today)

Create Your Own Module

Create a file named helpers.py.

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

Import it in another file.

from helpers import greet

print(greet("Alex"))

Common Built-In Functions

Print

print("Hello")

Length

print(len("Python"))

Range

for number in range(3):
    print(number)

Input

name = input("Enter your name: ")
print(f"Hello, {name}")

Enumerate

names = ["Alex", "Sam"]

for index, name in enumerate(names):
    print(index, name)

Zip

names = ["Alex", "Sam"]
scores = [90, 85]

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

Map

numbers = ["1", "2", "3"]

converted = list(map(int, numbers))

print(converted)

Filter

numbers = [1, 2, 3, 4, 5]

even_numbers = list(filter(lambda number: number % 2 == 0, numbers))

print(even_numbers)

List comprehensions are often easier to read than map() or filter().

Classes

Create a Class

class User:
    def __init__(self, name):
        self.name = name

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

Create an Object

user = User("Alex")

print(user.greet())

Instance Attributes

class Product:
    def __init__(self, title, price):
        self.title = title
        self.price = price

Inheritance

class Animal:
    def speak(self):
        return "Sound"


class Dog(Animal):
    def speak(self):
        return "Bark"


dog = Dog()
print(dog.speak())

Use classes when you need to group data and behavior together.

Dataclasses

Dataclasses reduce boilerplate for simple data objects.

from dataclasses import dataclass

@dataclass
class User:
    name: str
    age: int


user = User(name="Alex", age=28)
print(user)

Dataclasses are useful for models, configuration objects, and structured data.

Type Hints

Type hints make code easier to read and check.

def greet(name: str) -> str:
    return f"Hello, {name}"

Type Hints with Lists

def total(numbers: list[int]) -> int:
    return sum(numbers)

Type Hints with Dictionaries

def get_username(user: dict[str, str]) -> str:
    return user["name"]

Type hints do not change runtime behavior by themselves. They help editors, readers, and type checkers.

Virtual Environments

A virtual environment keeps project packages separate.

Create a Virtual Environment

python -m venv .venv

Activate on macOS or Linux

source .venv/bin/activate

Activate on Windows PowerShell

.venv\Scripts\Activate.ps1

Deactivate

deactivate

What to Look For

  • Your terminal prompt may show (.venv).
  • Packages install into the project environment.
  • Use one virtual environment per project.

Packages with pip

Install a Package

pip install requests

List Installed Packages

pip list

Save Dependencies

pip freeze > requirements.txt

Install Dependencies

pip install -r requirements.txt

Use requirements.txt when sharing a project or deploying it.

Working with JSON

Convert Dictionary to JSON

import json

user = {
    "name": "Alex",
    "age": 28
}

json_text = json.dumps(user)
print(json_text)

Convert JSON to Dictionary

import json

json_text = '{"name": "Alex", "age": 28}'
user = json.loads(json_text)

print(user["name"])

Read JSON from a File

import json

with open("user.json", "r", encoding="utf-8") as file:
    user = json.load(file)

print(user)

Write JSON to a File

import json

user = {
    "name": "Alex",
    "age": 28
}

with open("user.json", "w", encoding="utf-8") as file:
    json.dump(user, file, indent=4)

Dates and Times

Current Date

from datetime import date

today = date.today()
print(today)

Current Date and Time

from datetime import datetime

now = datetime.now()
print(now)

Format a Date

from datetime import datetime

now = datetime.now()
formatted = now.strftime("%Y-%m-%d")

print(formatted)

Parse a Date String

from datetime import datetime

date_text = "2026-06-23"
parsed_date = datetime.strptime(date_text, "%Y-%m-%d")

print(parsed_date)

Common Python Patterns

Count Items

items = ["apple", "banana", "apple"]

counts = {}

for item in items:
    counts[item] = counts.get(item, 0) + 1

print(counts)

Find the Largest Item

numbers = [10, 4, 25, 7]

largest = max(numbers)

print(largest)

Filter Data

users = [
    {"name": "Alex", "active": True},
    {"name": "Sam", "active": False},
    {"name": "Taylor", "active": True}
]

active_users = [user for user in users if user["active"]]

print(active_users)

Sort Dictionaries by a Value

users = [
    {"name": "Alex", "score": 90},
    {"name": "Sam", "score": 85}
]

users.sort(key=lambda user: user["score"], reverse=True)

print(users)

Check If a File Exists

from pathlib import Path

file_path = Path("data.txt")

if file_path.exists():
    print("File exists")
else:
    print("File missing")

Use main()

def main():
    print("Program started")


if __name__ == "__main__":
    main()

This pattern makes your file easier to run and import.

Common Mistakes

Wrong Indentation

if True:
print("Hello")

Better:

if True:
    print("Hello")

Python requires consistent indentation.

Using = Instead of ==

if age = 18:
    print("Adult")

Better:

if age == 18:
    print("Adult")

Use = for assignment and == for comparison.

Forgetting Quotes Around Strings

name = Alex

Better:

name = "Alex"

Without quotes, Python treats Alex as a variable name.

Modifying a List While Looping Over It

numbers = [1, 2, 3, 4]

for number in numbers:
    if number % 2 == 0:
        numbers.remove(number)

Better:

numbers = [1, 2, 3, 4]

numbers = [number for number in numbers if number % 2 != 0]

Create a new list when filtering.

Using Mutable Default Arguments

def add_item(item, items=[]):
    items.append(item)
    return items

Better:

def add_item(item, items=None):
    if items is None:
        items = []

    items.append(item)
    return items

Use None as the default when the value should be created fresh each time.

Debugging Tips

Print Values

print(user)

Print Labels

print("Current user:", user)

Check Types

print(type(value))

Use repr()

text = "hello\n"

print(repr(text))

repr() helps reveal hidden characters.

Use the Debugger

breakpoint()

Run the script, then inspect values when execution pauses.

Read Error Messages from the Bottom

The last line of a Python traceback usually tells you the error type and message.

Quick Reference

Print Output

print("Hello")

Create a Variable

name = "Alex"

Create a List

items = ["one", "two", "three"]

Create a Dictionary

user = {
    "name": "Alex",
    "age": 28
}

Write an if Statement

if age >= 18:
    print("Adult")

Write a Loop

for item in items:
    print(item)

Write a Function

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

Read a File

with open("data.txt", "r", encoding="utf-8") as file:
    content = file.read()

Handle an Error

try:
    number = int(value)
except ValueError:
    print("Invalid number")

Import a Module

import math

Create a Class

class User:
    def __init__(self, name):
        self.name = name

Create a Virtual Environment

python -m venv .venv