Python

Python syntax, built-in functions, and common patterns for efficient programming.

languages
pythonbackendscriptingdata

Variables & Data Types

# Variables (dynamic typing)
name = "Alice"          # str
age = 30               # int
height = 5.9           # float
is_active = True       # bool
items = [1, 2, 3]      # list
coords = (10, 20)      # tuple
person = {"name": "Bob"} # dict
unique = {1, 2, 3}     # set

# Type hints (Python 3.5+)
name: str = "Alice"
numbers: list[int] = [1, 2, 3]

# Multiple assignment
a, b, c = 1, 2, 3
x = y = z = 0

Strings

# String formatting
name = "World"
f"Hello, {name}!"           # f-strings (recommended)
"Hello, {}!".format(name)   # .format()
"Hello, %s!" % name         # % formatting

# String methods
s.upper()           # UPPERCASE
s.lower()           # lowercase
s.strip()           # Remove whitespace
s.split(",")        # Split into list
s.replace("a", "b") # Replace substring
s.startswith("Hi")  # Check prefix
s.endswith("!")     # Check suffix
"-".join(["a", "b"]) # Join list → "a-b"

Lists

# List operations
items = [1, 2, 3, 4, 5]
items.append(6)          # Add to end
items.insert(0, 0)       # Insert at index
items.pop()              # Remove & return last
items.remove(3)          # Remove first occurrence
items.extend([7, 8])     # Extend with iterable
len(items)               # Length

# Slicing
items[0]      # First element
items[-1]     # Last element
items[1:3]    # Elements 1-2
items[::2]    # Every 2nd element
items[::-1]   # Reversed

# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
matrix = [[i*j for j in range(3)] for i in range(3)]

Dictionaries

# Dictionary operations
d = {"name": "Alice", "age": 30}
d["name"]              # Get value (raises KeyError if missing)
d.get("name")          # Get value (returns None if missing)
d.get("job", "N/A")    # Get with default
d["job"] = "Developer" # Set value
d.keys()               # Get keys
d.values()             # Get values
d.items()              # Get key-value pairs
d.pop("age")           # Remove & return value
d.update({"city": "NYC"}) # Merge dictionaries

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}

Functions

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

# Default arguments
def greet(name="World"):
    return f"Hello, {name}!"

# *args and **kwargs
def func(*args, **kwargs):
    print(args)    # Tuple of positional args
    print(kwargs)  # Dict of keyword args

# Lambda functions
square = lambda x: x**2
add = lambda a, b: a + b

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

Control Flow

# If/elif/else
if condition:
    pass
elif other_condition:
    pass
else:
    pass

# Ternary operator
result = "yes" if condition else "no"

# For loops
for item in items:
    print(item)

for i, item in enumerate(items):
    print(i, item)

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

# While loops
while condition:
    pass

# Match statement (Python 3.10+)
match command:
    case "start":
        start()
    case "stop":
        stop()
    case _:
        unknown()

Classes

class Person:
    # Class variable
    species = "Human"
    
    def __init__(self, name, age):
        # Instance variables
        self.name = name
        self.age = age
        self._protected = "protected"
        self.__private = "private"
    
    # Instance method
    def greet(self):
        return f"Hello, I'm {self.name}"
    
    # Class method
    @classmethod
    def create_anonymous(cls):
        return cls("Anonymous", 0)
    
    # Static method
    @staticmethod
    def is_adult(age):
        return age >= 18
    
    # Property
    @property
    def info(self):
        return f"{self.name}, {self.age}"
    
    # String representation
    def __str__(self):
        return f"Person({self.name})"

# Inheritance
class Developer(Person):
    def __init__(self, name, age, language):
        super().__init__(name, age)
        self.language = language

File Operations

# Reading files
with open("file.txt", "r") as f:
    content = f.read()        # Read entire file
    lines = f.readlines()     # Read as list of lines

# Writing files
with open("file.txt", "w") as f:
    f.write("Hello, World!")

# Appending to files
with open("file.txt", "a") as f:
    f.write("New line\n")

# JSON
import json
data = json.loads(json_string)  # Parse JSON
json_string = json.dumps(data)  # Convert to JSON

Error Handling

try:
    result = risky_operation()
except ValueError as e:
    print(f"Value error: {e}")
except (TypeError, KeyError):
    print("Type or Key error")
except Exception as e:
    print(f"Unexpected error: {e}")
else:
    print("No errors occurred")
finally:
    print("Always executes")

# Raising exceptions
raise ValueError("Invalid value")

# Custom exceptions
class CustomError(Exception):
    pass

Useful Built-ins

# Common functions
len(obj)           # Length
range(start, stop, step)
enumerate(iterable)
zip(iter1, iter2)
map(func, iterable)
filter(func, iterable)
sorted(iterable, key=func, reverse=False)
any(iterable)      # True if any element is truthy
all(iterable)      # True if all elements are truthy
min(iterable)
max(iterable)
sum(iterable)
abs(number)
round(number, digits)
isinstance(obj, type)
type(obj)
dir(obj)           # List attributes
help(obj)          # Get documentation