Essential Python syntax, data structures, comprehensions, and common patterns for quick reference
Basic Syntax
Variables
Python uses dynamic typing - no type declaration needed
# Variables (dynamically typed)
x = 5
name = "John"
is_active = True String Formatting
f-strings (Python 3.6+) or str.format() method
name = "Alice"
age = 25
print(f"Hello, {name}. You are {age} years old")
print("Hello, {}. You are {} years old".format(name, age)) Conditional Statements
Use indentation to define code blocks
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child") Data Structures
Lists
Ordered, mutable collections
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits[0] # "apple"
fruits[-1] # "orange" (last item)
fruits[1:3] # ["banana", "cherry"] (slice) Dictionaries
Key-value pairs, like objects in JavaScript
person = {"name": "John", "age": 30}
person["city"] = "New York"
person.get("name") # "John"
person.keys() # dict_keys(['name', 'age', 'city']) Sets
Unordered collection of unique elements
unique_nums = {1, 2, 3, 3, 4} # {1, 2, 3, 4}
unique_nums.add(5)
unique_nums.remove(1) Tuples
Immutable ordered collections
coordinates = (10, 20)
x, y = coordinates # Unpacking
immutable = (1, 2, 3) # Cannot be modified List Comprehensions
Basic Comprehension
Create lists in a single line
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] With Condition
Filter elements with if condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64] Dict Comprehension
Create dictionaries efficiently
square_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} Functions
Basic Function
Functions with default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Bob", "Hi") # "Hi, Bob!" Lambda Functions
Anonymous functions for simple operations
square = lambda x: x**2
numbers = [1, 2, 3, 4]
squared = list(map(square, numbers)) # [1, 4, 9, 16] Decorators
Modify function behavior without changing its code
def uppercase_decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@uppercase_decorator
def greet(name):
return f"hello, {name}"
greet("alice") # "HELLO, ALICE" Classes
Basic Class
__init__ is the constructor method
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}"
person = Person("John", 30)
print(person.greet()) # "Hi, I'm John" Inheritance
Inherit from parent class using super()
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def study(self):
return f"{self.name} is studying" Find this helpful?
Check out more cheatsheets and learning resources, or get in touch for personalized training.