beginner languages Python 3.12 · Updated April 2026

Python Basics Cheatsheet

Master Python fundamentals quickly with this cheatsheet covering core concepts, syntax, and common patterns for Python 3.12.

· 8 min read · AI-reviewed

Quick Overview

Python is a versatile, high-level, interpreted programming language renowned for its readability and simplicity. It supports multiple programming paradigms, including object-oriented, imperative, and functional programming. Developers use Python for web development (Django, Flask), data science (NumPy, Pandas), AI/ML, automation, scripting, and more, making it an excellent language for beginners and experienced professionals alike. The examples in this guide are for Python 3.12.

Current Stable Version: As of early 2026, Python 3.14.3 is the latest stable release, but Python 3.12.13 is also a recently maintained stable version, released on March 3, 2026. Install: Download the installer from python.org

Getting Started

To get Python 3.12 running on your machine, follow these steps. For Windows, ensure “Add Python to PATH” is checked during installation.

  1. Download Python 3.12: Visit the official Python download page: python.org/downloads Download the installer for your operating system (e.g., Windows installer, macOS installer).

  2. Install Python: Run the downloaded installer. Important: On Windows, make sure to check the box that says “Add Python X.Y to PATH” during installation. This allows you to run Python from any command prompt.

  3. Verify Installation: Open your terminal or command prompt and run:

    # Check Python version
    python --version
    # Expected output similar to: Python 3.12.x
  4. Run Your First Python Script: Create a file named hello.py with your favorite text editor:

    # hello.py
    print("Hello, z2h.fyi!")

    Save the file, then run it from your terminal:

    # Run the Python script
    python hello.py
    # Expected output: Hello, z2h.fyi!
  5. Use the Interactive Interpreter (REPL): Type python in your terminal to enter the interactive mode. You can execute Python code line by line.

    # Start the Python interpreter
    python
    # Inside the interpreter
    >>> print("Hello, interactive Python!")
    Hello, interactive Python!
    >>> 2 + 3
    5
    >>> exit() # Type exit() or Ctrl+D (Linux/macOS) / Ctrl+Z then Enter (Windows) to exit

Core Concepts

ConceptDescription
VariablesNamed storage locations for data. Python is dynamically typed, so you don’t declare a variable’s type.
Data TypesCategories of data, such as numbers (integers, floats), strings, booleans, lists, tuples, dictionaries, and sets.
OperatorsSymbols that perform operations on values and variables (e.g., arithmetic +, comparison ==, logical and).
Control FlowDirects the order in which instructions are executed using constructs like if/elif/else (conditionals) and for/while (loops). Python uses indentation for code blocks.
FunctionsReusable blocks of code that perform a specific task. They promote modularity and reduce code duplication.
ModulesPython files (.py) containing code (functions, classes, variables) that can be imported and used in other Python files.
ObjectsEverything in Python is an object, meaning it has an identity, type, and value. This underpins Python’s object-oriented nature.

Essential Commands / API / Syntax

Variables and Assignment

Python variables are dynamically typed; you don’t declare their type.

# Assign a string to a variable
name = "Alice"
# Assign an integer
age = 30
# Assign a float
height = 1.75
# Assign a boolean
is_student = True

Basic Data Types

# Integer
my_int = 10

# Float
my_float = 3.14

# String (single or double quotes)
my_string = "Hello, Python!"

# Boolean
my_bool = True
another_bool = False

# NoneType (represents absence of a value)
empty_value = None

Operators

# Arithmetic Operators
a, b = 10, 3
print(f"Addition: {a + b}")       # 13
print(f"Subtraction: {a - b}")    # 7
print(f"Multiplication: {a * b}") # 30
print(f"Division: {a / b}")       # 3.333... (float division)
print(f"Floor Division: {a // b}")# 3 (integer division)
print(f"Modulo: {a % b}")         # 1 (remainder)
print(f"Exponentiation: {a ** b}")# 1000 (10^3)

# Comparison Operators
print(f"Equal: {a == b}")         # False
print(f"Not Equal: {a != b}")     # True
print(f"Greater Than: {a > b}")    # True
print(f"Less Than: {a < b}")      # False
print(f"Greater or Equal: {a >= b}") # True
print(f"Less or Equal: {a <= b}") # False

# Logical Operators (and, or, not)
x, y = True, False
print(f"AND: {x and y}")          # False
print(f"OR: {x or y}")            # True
print(f"NOT: {not x}")            # False

Strings

Strings are immutable sequences of characters.

# String creation
greeting = "Hello"
name = 'World'
message = greeting + ", " + name + "!" # Concatenation
print(message) # Hello, World!

# String formatting (f-strings, new in Python 3.6, enhanced in 3.12)
# Python 3.12 allows more flexible f-strings, including nested quotes and comments
user = "Alice"
age = 30
formatted_message = f"User: {user}, Age: {age}."
print(formatted_message) # User: Alice, Age: 30.

# Multi-line f-string (Python 3.12+)
long_message = (
    f"This is a message "
    f"from {user} "
    f"on multiple lines."
)
print(long_message) # This is a message from Alice on multiple lines.

# String methods
s = "  Python Programming  "
print(s.upper())            # PYTHON PROGRAMMING
print(s.lower())            #   python programming
print(s.strip())            # Python Programming (removes leading/trailing whitespace)
print(s.replace("Python", "Java")) #   Java Programming
print("Code".startswith("Co")) # True
print("Code".endswith("de"))   # True
print("1,2,3".split(','))   # ['1', '2', '3']
print("-".join(["a", "b", "c"])) # a-b-c

Lists

Ordered, mutable collections.

# List creation
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]

# Accessing elements (0-indexed)
print(fruits[0])  # apple
print(numbers[-1])# 5 (last element)

# Slicing
print(numbers[1:4]) # [2, 3, 4] (elements from index 1 up to, but not including, 4)
print(numbers[:3])  # [1, 2, 3] (from beginning to index 3)
print(numbers[2:])  # [3, 4, 5] (from index 2 to end)

# Modifying lists
fruits.append("date")         # Add to end: ["apple", "banana", "cherry", "date"]
fruits.insert(1, "grape")     # Insert at index 1: ["apple", "grape", "banana", "cherry", "date"]
fruits.remove("banana")       # Remove by value: ["apple", "grape", "cherry", "date"]
popped_fruit = fruits.pop()   # Remove and return last: "date"
del fruits[0]                 # Delete by index: ["grape", "cherry"]
fruits[0] = "kiwi"            # Modify element: ["kiwi", "cherry"]

# List methods
print(len(fruits))            # 2
numbers.sort()                # Sort in place
sorted_numbers = sorted(numbers, reverse=True) # Returns new sorted list

Tuples

Ordered, immutable collections. Useful for fixed data.

# Tuple creation
coordinates = (10.0, 20.0)
colors = ("red", "green", "blue")

# Accessing elements (like lists)
print(coordinates[0]) # 10.0

# Tuples are immutable; this would raise an error:
# coordinates[0] = 15.0

# Unpacking tuples
lat, lon = coordinates
print(f"Latitude: {lat}, Longitude: {lon}") # Latitude: 10.0, Longitude: 20.0

Dictionaries

Unordered, mutable collections of key-value pairs. Keys must be unique and immutable.

# Dictionary creation
person = {"name": "Charlie", "age": 25, "city": "New York"}

# Accessing values
print(person["name"])    # Charlie
print(person.get("age")) # 25 (safer, returns None if key not found)

# Modifying dictionaries
person["age"] = 26       # Update value
person["email"] = "[email protected]" # Add new key-value pair

# Removing elements
del person["city"]       # Remove by key
age = person.pop("age")  # Remove and return value

# Dictionary methods
print(person.keys())     # dict_keys(['name', 'email'])
print(person.values())   # dict_values(['Charlie', '[email protected]'])
print(person.items())    # dict_items([('name', 'Charlie'), ('email', '[email protected]')])

# Iterate through dictionary
for key, value in person.items():
    print(f"{key}: {value}")

Sets

Unordered collections of unique, immutable elements. Useful for membership testing and mathematical set operations.

# Set creation
unique_numbers = {1, 2, 3, 3, 4} # {1, 2, 3, 4} (duplicates removed)
fruits_set = {"apple", "banana", "cherry"}

# Adding/Removing elements
fruits_set.add("orange")
fruits_set.remove("banana") # Raises KeyError if not present
print(fruits_set) # {'cherry', 'orange', 'apple'} (order may vary)

# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print(set_a.union(set_b))        # {1, 2, 3, 4, 5, 6}
print(set_a.intersection(set_b)) # {3, 4}
print(set_a.difference(set_b))   # {1, 2}

Control Flow: Conditionals

# if / elif / else
score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

Control Flow: Loops

# for loop (iterating over sequences)
for fruit in ["apple", "banana", "cherry"]:
    print(f"I like {fruit}")

# for loop with range()
# range(stop): 0 to stop-1
# range(start, stop): start to stop-1
# range(start, stop, step): start to stop-1, with step
for i in range(3): # 0, 1, 2
    print(i)

for i in range(1, 4): # 1, 2, 3
    print(i)

# while loop
count = 0
while count < 3:
    print(f"Count: {count}")
    count += 1 # Increment count

Functions

Define reusable blocks of code.

# Simple function definition
def greet(name):
    return f"Hello, {name}!"

print(greet("Eve")) # Hello, Eve!

# Function with default arguments
def multiply(a, b=2):
    return a * b

print(multiply(5))    # 10 (b uses default 2)
print(multiply(5, 3)) # 15 (b overrides default)

# Function with arbitrary arguments (*args for positional, **kwargs for keyword)
def log_details(message, *args, **kwargs):
    print(f"Message: {message}")
    if args:
        print(f"Positional args: {args}")
    if kwargs:
        print(f"Keyword args: {kwargs}")

log_details("User event", 1, 2, level="INFO", timestamp="2026-01-01")
# Message: User event
# Positional args: (1, 2)
# Keyword args: {'level': 'INFO', 'timestamp': '2026-01-01'}

# Type hints (new type statement in 3.12 for type aliases)
# The 'type' keyword for type aliases simplifies syntax
type Point = tuple[float, float]

def get_distance(p1: Point, p2: Point) -> float:
    """Calculates Euclidean distance between two points."""
    x1, y1 = p1
    x2, y2 = p2
    return ((x2 - x1)**2 + (y2 - y1)**2)**0.5

point_a: Point = (0.0, 0.0)
point_b: Point = (3.0, 4.0)
print(f"Distance: {get_distance(point_a, point_b)}") # Distance: 5.0

Modules and Packages

Organize code into reusable files (.py) and directories.

# math_operations.py
# def add(a, b):
#     return a + b
# def subtract(a, b):
#     return a - b

# main.py
# Import an entire module
import math
print(math.sqrt(16)) # 4.0

# Import specific functions from a module
from datetime import datetime, timedelta
now = datetime.now()
print(f"Current time: {now}")
next_hour = now + timedelta(hours=1)
print(f"Time in one hour: {next_hour}")

# Import your own module
# Assuming math_operations.py is in the same directory
# from math_operations import add, subtract
# print(add(10, 5)) # 15

Input/Output

# Get input from the user
user_name = input("Enter your name: ")
print(f"Hello, {user_name}!")

# Writing to a file
with open("output.txt", "w") as f: # "w" for write, creates/overwrites file
    f.write("This is a line of text.\n")
    f.write("This is another line.\n")

# Reading from a file
with open("output.txt", "r") as f: # "r" for read
    content = f.read() # Reads entire file content
    print(content)

# Reading line by line
with open("output.txt", "r") as f:
    for line in f:
        print(f"Line: {line.strip()}") # .strip() removes newline characters

Error Handling

Use try, except, else, finally to manage errors.

try:
    result = 10 / 0 # This will cause a ZeroDivisionError
except ZeroDivisionError:
    print("Cannot divide by zero!")
except TypeError:
    print("Type error occurred!")
except Exception as e: # Catch any other exception
    print(f"An unexpected error occurred: {e}")
else: # Executes if no exception occurs in try block
    print("Division successful.")
finally: # Always executes, regardless of exception
    print("Execution finished.")

# Example with a valid division
try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print(f"Result: {result}") # Result: 5.0
finally:
    print("Always runs.")

Common Patterns

Reading and Writing JSON Data

import json

data = {
    "name": "Alice",
    "age": 30,
    "isStudent": False,
    "courses": ["Math", "Science"]
}

# Write JSON to a file
with open("data.json", "w") as f:
    json.dump(data, f, indent=4) # indent makes it human-readable

# Read JSON from a file
with open("data.json", "r") as f:
    loaded_data = json.load(f)
    print(f"Loaded data: {loaded_data['name']}") # Loaded data: Alice

List Comprehensions

A concise way to create lists. Often faster due to optimizations, especially in Python 3.12.

# Create a list of squares
squares = [x * x for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]

# Filter and transform with a condition
even_squares = [x * x for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]

# Dictionary comprehension
squares_dict = {x: x*x for x in range(5)}
print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Simple Command-Line Argument Parsing

Using the sys module for basic arguments or argparse for more complex needs.

# myscript.py
import sys

# Basic argument parsing (for `python myscript.py arg1 arg2`)
if __name__ == "__main__":
    if len(sys.argv) > 1:
        print(f"First argument: {sys.argv[1]}")
    else:
        print("No arguments provided.")

# Run from terminal:
# python myscript.py hello
# Output: First argument: hello

Gotchas & Tips

  • Indentation is Key: Python uses whitespace (specifically indentation) to define code blocks, unlike other languages that use braces {}. Incorrect indentation will lead to IndentationError. Use 4 spaces for indentation, consistently.

  • Mutable vs. Immutable Types:

    • Immutable: int, float, str, tuple, bool. Once created, their value cannot be changed. Operations on them create new objects.
    • Mutable: list, dict, set. Their contents can be modified in place after creation. Be careful when passing mutable objects to functions or assigning them, as changes will affect all references.
    # Mutable example
    my_list = [1, 2, 3]
    another_list = my_list # Both variables reference the SAME list
    another_list.append(4)
    print(my_list) # [1, 2, 3, 4] - my_list was also modified!
    
    # Immutable example
    my_string = "hello"
    another_string = my_string
    my_string += " world" # Creates a NEW string, doesn't modify the original
    print(another_string) # hello - another_string still refers to the original
  • Scope: Variables defined inside a function are local to that function. Variables defined outside are global. Avoid modifying global variables directly inside functions; pass them as arguments or return new values.

  • Improved Error Messages (Python 3.12+): Python 3.12 includes significantly improved error messages, especially for typos and common mistakes, making debugging easier for beginners.

  • F-strings for Readability: Always prefer f-strings (formatted string literals) for string formatting as they are readable, concise, and performant. Python 3.12 makes them even more powerful by allowing previously disallowed expressions, including those with quotes or backslashes.

  • Python Enhancement Proposals (PEPs): Python development is guided by PEPs. For example, PEP 701 brought the syntactic formalization of f-strings in 3.12. Knowing about PEPs can help understand language evolution.

Next Steps

  • Official Python Documentation: The most comprehensive and authoritative resource. docs.python.org/3.12/
  • Real Python: Excellent tutorials and guides for all levels. realpython.com
  • Automate the Boring Stuff with Python: A practical book for using Python for automation.
  • z2h.fyi/cheatsheets/python-advanced: (If this existed, it would be linked here)
  • Practice: The best way to learn is by doing. Try solving small problems on platforms like LeetCode or HackerRank, or build small projects.

Source: z2h.fyi/cheatsheets/python-basics — Zero to Hero cheatsheets for developers.