Python Basics Cheat Sheet

New

Python syntax, data types, control flow, functions, and file I/O

Data Types

Numeric Types

int, float, complex — arithmetic and conversions

x = 42 # int y = 3.14 # float z = 2 + 3j # complex int("10") # convert string to int

Strings

Immutable sequences of characters

name = "Alice" greeting = f"Hello, {name}!" # f-string multi = """line1 line2"""

Booleans & None

True/False and the null value None

is_active = True result = None bool(0) # False bool("hi") # True

String Methods

Common Methods

Frequently used string transformation methods

s = " Hello, World! " s.strip() # "Hello, World!" s.lower() # " hello, world! " s.upper() # " HELLO, WORLD! " s.replace("Hello", "Hi") # " Hi, World! " s.split(", ") # [" Hello", "World! "]

Slicing & Formatting

Slice strings and format output

s = "Python" s[0:3] # "Pyt" s[-3:] # "hon" f"{42:.2f}" # "42.00" f"{"hi":>10}" # " hi"

Control Flow

if / elif / else

Conditional execution

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

for loop

Iterate over sequences and ranges

for i in range(5): # 0,1,2,3,4 print(i) for item in my_list: print(item) for i, v in enumerate(lst): print(i, v)

while loop

Loop while condition is true

while count < 10: count += 1 if count == 5: continue # skip to next if count == 8: break # exit loop

List Comprehensions

Concise way to create filtered/transformed lists

squares = [x**2 for x in range(10)] evens = [x for x in range(20) if x % 2 == 0] matrix = [[r*c for c in range(3)] for r in range(3)]

Functions

def & return

Define a function with typed hints

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

*args & **kwargs

Accept variable positional and keyword arguments

def total(*args: int) -> int: return sum(args) def display(**kwargs: str) -> None: for k, v in kwargs.items(): print(f"{k}: {v}")

Lambda Functions

Anonymous one-line functions

square = lambda x: x ** 2 sorted_data = sorted(items, key=lambda x: x["age"])

List Operations

List Methods

Modify and query lists in-place or return new values

lst = [3, 1, 4, 1, 5] lst.append(9) # [3,1,4,1,5,9] lst.extend([2, 6]) # extends in-place lst.insert(0, 0) # insert at index lst.remove(1) # removes first 1 lst.pop() # removes & returns last lst.sort() # sort in-place lst.reverse() # reverse in-place

Dictionary Operations

Dict Methods

Common dictionary operations

d = {"name": "Alice", "age": 30} d.get("email", "N/A") # safe get with default d.update({"city": "NYC"}) # merge/update list(d.keys()) # ["name", "age", "city"] list(d.values()) # ["Alice", 30, "NYC"] list(d.items()) # [("name","Alice"), ...]

File I/O

Read & Write Files

Open files safely using context managers

# Read a file with open("data.txt", "r") as f: content = f.read() lines = f.readlines() # Write a file with open("output.txt", "w") as f: f.write("Hello\n") f.writelines(["line1\n", "line2\n"])

Common Patterns

List Comprehension

Concise data transformation with filtering

numbers = range(1, 21)

# Basic transformation
squares = [n**2 for n in numbers]

# With filter
even_squares = [n**2 for n in numbers if n % 2 == 0]

# Nested
pairs = [(x, y) for x in range(3) for y in range(3) if x != y]

# Dict comprehension
word_lengths = {word: len(word) for word in ["python", "is", "great"]}

Dictionary Comprehension

Build and transform dictionaries concisely

inventory = {"apple": 5, "banana": 0, "orange": 3}

# Invert a dict
inverted = {v: k for k, v in inventory.items()}

# Filter dict
in_stock = {k: v for k, v in inventory.items() if v > 0}
# {"apple": 5, "orange": 3}

# Transform values
doubled = {k: v * 2 for k, v in inventory.items()}

Context Manager

Use with statement for safe resource handling

import json

# Read JSON file
with open("config.json", "r") as f:
    config = json.load(f)

# Write JSON file
with open("output.json", "w") as f:
    json.dump({"key": "value"}, f, indent=2)

# Multiple context managers
with open("input.txt") as src, open("output.txt", "w") as dst:
    dst.write(src.read().upper())

Tips & Best Practices

Use f-strings (f"Hello {name}") over .format() or % formatting

Prefer enumerate() over range(len(lst)) when you need both index and value

Always use with when opening files to ensure they are properly closed

Use list comprehensions for simple transformations, but regular loops for complex logic

Add type hints to function signatures for better IDE support and documentation