Quick syntax snippets, code examples, and essential patterns – all in one place. Copy, paste, and level up.
Core syntax: variables, data types, basic operators, and input/output.
Declare variables with dynamic typing – no type declaration needed.
# Variable assignment name = "Alice" age = 30 height = 5.8 is_student = True # Multiple assignment a, b, c = 1, 2, 3 # Type checking print(type(name)) # <class 'str'> print(type(age)) # <class 'int'>
Python's core built-in data types – int, float, str, bool, None.
# Numeric types
integer = 42
floating = 3.14159
complex_num = 2 + 3j
# Text type
text = "Hello, World!"
# Boolean & None
flag = False
nothing = None
# Type conversion
num_str = str(100) # "100"
num_int = int("200") # 200
Standard math operators plus floor division and exponentiation.
# Basic arithmetic sum_val = 10 + 5 # 15 diff = 10 - 5 # 5 prod = 10 * 5 # 50 quot = 10 / 3 # 3.333... # Special operators floor_div = 10 // 3 # 3 (integer division) modulo = 10 % 3 # 1 (remainder) power = 2 ** 8 # 256 (exponentiation)
Boolean expressions with comparison and logical operators.
# Comparison operators x, y = 10, 20 print(x == y) # False print(x != y) # True print(x < y) # True print(x >= 10) # True # Logical operators print(x > 5 and y < 30) # True print(x > 15 or y < 30) # True print(not x > 15) # True # Chained comparison print(5 < x < 15) # True
Reading user input and printing formatted output.
# Reading input (always returns string)
user_name = input("Enter your name: ")
# Basic printing
print("Hello,", user_name)
# f-strings (Python 3.6+)
age = 25
print(f"{user_name} is {age} years old.")
# Format specifiers
pi = 3.14159265
print(f"Pi ≈ {pi:.2f}") # Pi ≈ 3.14
# sep & end parameters
print("A", "B", "C", sep="-") # A-B-C
print("Line 1", end=" | ")
print("Line 2") # Line 1 | Line 2
Conditional statements, loops, and control flow keywords.
Conditional branching based on boolean expressions.
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
print(f"Grade: {grade}") # Grade: B
# Ternary (conditional expression)
status = "Pass" if score >= 60 else "Fail"
Iterate over sequences – lists, strings, ranges, and more.
# Looping over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using range()
for i in range(5): # 0 to 4
print(i, end=" ") # 0 1 2 3 4
for i in range(2, 8, 2): # start=2, stop=8, step=2
print(i, end=" ") # 2 4 6
# Looping over dict keys/values
person = {"name": "Alice", "age": 30}
for key, value in person.items():
print(f"{key}: {value}")
Repeat a block while a condition remains true.
# Basic while loop
count = 0
while count < 5:
print(count, end=" ")
count += 1
# Output: 0 1 2 3 4
# while with break & continue
num = 0
while True:
num += 1
if num == 3:
continue # skip 3
if num > 6:
break # exit loop
print(num, end=" ")
# Output: 1 2 4 5 6
Control loop execution with break, continue, and pass.
# break - exit loop entirely
for i in range(10):
if i == 5:
break
print(i, end=" ") # 0 1 2 3 4
# continue - skip current iteration
for i in range(6):
if i % 2 == 0:
continue
print(i, end=" ") # 1 3 5
# pass - do nothing (placeholder)
def future_function():
pass # TODO: implement later
Structural pattern matching – Python's switch-case equivalent.
# Python 3.10+ pattern matching
def handle_command(cmd):
match cmd:
case "start":
return "Starting..."
case "stop":
return "Stopping..."
case "pause" | "resume":
return "Toggling state..."
case _:
return "Unknown command"
print(handle_command("pause")) # Toggling state...
Defining functions, arguments, return values, lambda expressions, and decorators.
Define reusable blocks with def, parameters, and return values.
# Basic function
def greet(name):
"""Return a greeting message."""
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
# Multiple return values (tuple unpacking)
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 7, 2, 9])
print(low, high) # 1 9
Positional, keyword, default, *args, and **kwargs explained.
# Default parameters
def power(base, exp=2):
return base ** exp
print(power(5)) # 25 (exp defaults to 2)
print(power(2, 10)) # 1024
# *args (variable positional)
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4)) # 10
# **kwargs (variable keyword)
def print_info(**kwargs):
for k, v in kwargs.items():
print(f"{k}: {v}")
print_info(name="Bob", age=25)
Anonymous single-expression functions for concise callbacks.
# Basic lambda square = lambda x: x ** 2 print(square(7)) # 49 # Lambda with multiple args add = lambda a, b: a + b print(add(3, 5)) # 8 # Used with built-in functions numbers = [1, 2, 3, 4, 5] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4] # Sorting with lambda pairs = [(1, 3), (4, 1), (2, 2)] pairs.sort(key=lambda p: p[1]) print(pairs) # [(4, 1), (2, 2), (1, 3)]
Wrap functions to extend behaviour without modifying them.
# Simple decorator
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time()-start:.4f}s")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(0.5)
return "Done"
print(slow_function())
Lists, tuples, dictionaries, sets, and common operations on each.
Ordered, mutable sequences – Python's workhorse data structure.
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]
# Indexing & slicing
print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(fruits[1:3]) # ['banana', 'cherry']
# Common methods
fruits.append("date")
fruits.insert(1, "blueberry")
fruits.remove("banana")
popped = fruits.pop() # removes last
fruits.sort(reverse=True)
Ordered, immutable sequences – perfect for fixed collections.
# Creating tuples
point = (3, 4)
colors = "red", "green", "blue" # packing
# Unpacking
x, y = point
print(x, y) # 3 4
# Single-element tuple (note comma!)
single = (42,)
# Named tuples
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age'])
alice = Person(name="Alice", age=30)
print(alice.name, alice.age)
Key-value pairs – fast lookups, flexible keys (hashable types).
# Creating dicts
person = {"name": "Alice", "age": 30}
scores = dict(math=95, english=88)
# Access & modify
print(person["name"]) # Alice
print(person.get("city", "N/A")) # N/A (safe access)
person["city"] = "New York"
# Looping
for key, value in person.items():
print(f"{key}: {value}")
# Dict comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Unordered collections of unique elements with set operations.
# Creating sets
a = {1, 2, 3, 4}
b = set([3, 4, 5, 6])
# Set operations
print(a | b) # Union: {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric diff: {1, 2, 5, 6}
# Useful methods
a.add(5)
a.remove(2)
print(3 in a) # True (fast membership test)
String formatting, slicing, common methods, and f-string tricks.
Common string manipulation methods for everyday use.
text = " Hello, Python World! "
# Stripping whitespace
print(text.strip()) # "Hello, Python World!"
print(text.lstrip()) # left strip
print(text.rstrip()) # right strip
# Case conversion
print(text.upper()) # " HELLO, PYTHON WORLD! "
print(text.lower())
print(text.title()) # " Hello, Python World! "
# Find & replace
print(text.replace("Python", "Java"))
print(text.find("World")) # 15 (index)
Modern string interpolation with expressions and format specs.
name = "Alice"
age = 30
pi = 3.14159265
# Basic interpolation
print(f"{name} is {age} years old.")
# Expressions inside f-strings
print(f"Next year: {age + 1}")
# Format specifiers
print(f"Pi: {pi:.3f}") # 3.142
print(f"Percent: {0.875:.1%}") # 87.5%
print(f"Hex: {255:#x}") # 0xff
print(f"Padded: {42:05d}") # 00042
# Alignment
print(f"{'Left':<10}|{'Right':>10}")
Extract substrings using [start:stop:step] notation.
text = "Hello, World!"
# Basic slicing
print(text[0:5]) # "Hello"
print(text[7:]) # "World!"
print(text[:5]) # "Hello"
print(text[-6:-1]) # "World"
# With step
print(text[::2]) # "Hlo ol!" (every 2nd char)
print(text[::-1]) # "!dlroW ,olleH" (reverse)
# Slice assignment (lists)
chars = list(text)
chars[7:12] = list("Earth")
print(''.join(chars)) # "Hello, Earth!"
Convert between strings and lists with join() and split().
# split() - string to list
csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits) # ['apple', 'banana', 'cherry']
# split with maxsplit
line = "a b c d e"
print(line.split(" ", 2)) # ['a', 'b', 'c d e']
# join() - list to string
words = ["Hello", "World"]
sentence = " ".join(words)
print(sentence) # "Hello World"
# join with different separator
path = "/".join(["usr", "local", "bin"])
print(path) # "usr/local/bin"
Concise ways to create lists, dicts, and sets with conditional filtering.
Create lists in a single line – faster and more Pythonic than loops.
# Basic squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # With conditional filter evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # With if/else (ternary) labels = ["even" if x % 2 == 0 else "odd" for x in range(6)] # ['even', 'odd', 'even', 'odd', 'even', 'odd'] # Nested loops pairs = [(x, y) for x in range(3) for y in range(2)] # [(0,0), (0,1), (1,0), (1,1), (2,0), (2,1)]
Build dictionaries and sets using the same compact syntax.
# Dict comprehension
square_map = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Filtering dict
ages = {"Alice": 30, "Bob": 25, "Charlie": 35}
adults = {k: v for k, v in ages.items() if v >= 30}
# {'Alice': 30, 'Charlie': 35}
# Set comprehension
unique_lengths = {len(word) for word in ["hi", "hello", "hey", "world"]}
# {2, 3, 5}
# Generator expression (memory-efficient)
sum_of_squares = sum(x**2 for x in range(1000000))
Reading from and writing to files, context managers, and path handling.
Open and read files safely using context managers (with statement).
# Read entire file
with open("data.txt", "r") as f:
content = f.read()
# Read line by line
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
# Read all lines into a list
with open("data.txt", "r") as f:
lines = f.readlines()
# Read with encoding
with open("data.txt", "r", encoding="utf-8") as f:
text = f.read()
Write data to files – overwrite, append, and create new files.
# Write (overwrites)
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.write("Second line.\n")
# Append (adds to end)
with open("log.txt", "a") as f:
f.write(f"New log entry at {time.ctime()}\n")
# Write multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
# Create file if not exists (x mode)
try:
with open("new_file.txt", "x") as f:
f.write("Fresh file!")
except FileExistsError:
print("File already exists")
Use pathlib for modern, cross-platform file path handling.
from pathlib import Path
# Create Path object
p = Path("/usr/local/bin/script.py")
# Path properties
print(p.name) # script.py
print(p.stem) # script
print(p.suffix) # .py
print(p.parent) # /usr/local/bin
# Check existence
if p.exists():
print("File exists!")
# Iterate over directory
for file in Path(".").glob("*.py"):
print(file.name)
# Create directory
Path("new_folder").mkdir(exist_ok=True)
Classes, inheritance, dunder methods, properties, and object-oriented patterns.
Define classes with __init__, attributes, and instance methods.
class Dog:
"""A simple Dog class."""
species = "Canis familiaris" # class attribute
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age
def bark(self):
return f"{self.name} says Woof!"
def __str__(self):
return f"{self.name} ({self.age} years)"
# Creating instances
buddy = Dog("Buddy", 3)
print(buddy.bark()) # Buddy says Woof!
print(str(buddy)) # Buddy (3 years)
Extend classes with inheritance and super() for parent access.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name)
self.color = color
def speak(self):
return f"{self.name} says Meow!"
def describe(self):
return f"{self.color} cat named {self.name}"
cat = Cat("Whiskers", "orange")
print(cat.speak()) # Whiskers says Meow!
print(cat.describe()) # orange cat named Whiskers
Magic/dunder methods for operator overloading and built-in behaviour.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1 + v2) # Vector(6, 8)
print(v1 * 3) # Vector(6, 9)
print(v1 == v2) # False
Create managed attributes with getters, setters, and deleters.
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
"""Getter for radius."""
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
@property
def area(self):
"""Computed property – no setter needed."""
import math
return math.pi * self._radius ** 2
c = Circle(5)
print(c.area) # 78.539...
c.radius = 10
print(c.area) # 314.159...
Generators, context managers, exception handling, and advanced patterns.
Handle errors gracefully with exception handling blocks.
try:
num = int(input("Enter a number: "))
result = 100 / num
print(f"Result: {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No errors occurred!")
finally:
print("Execution complete.")
Create memory-efficient iterators using yield instead of return.
# Generator function
def fibonacci(n):
"""Generate first n Fibonacci numbers."""
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# Using the generator
for num in fibonacci(10):
print(num, end=" ")
# 0 1 1 2 3 5 8 13 21 34
# Generator expression
squares = (x**2 for x in range(1000000))
print(next(squares)) # 0
print(next(squares)) # 1
Create custom context managers with __enter__ and __exit__.
# Custom context manager class
class Timer:
def __enter__(self):
import time
self.start = time.time()
return self
def __exit__(self, *args):
import time
elapsed = time.time() - self.start
print(f"Elapsed: {elapsed:.4f}s")
with Timer():
# Some work
sum(range(10000000))
# Using contextlib
from contextlib import contextmanager
@contextmanager
def temp_dir():
import tempfile, shutil, os
dirpath = tempfile.mkdtemp()
try:
yield dirpath
finally:
shutil.rmtree(dirpath)
Add optional static type annotations for better code clarity.
from typing import List, Dict, Optional, Union
# Function with type hints
def greet(name: str, age: int) -> str:
return f"{name} is {age} years old."
# Complex types
def process_items(
items: List[int],
mapping: Dict[str, float]
) -> Optional[Dict[str, Union[int, float]]]:
if not items:
return None
return {str(k): float(v) for k, v in zip(items, mapping.values())}
# Variable annotation
count: int = 0
names: List[str] = ["Alice", "Bob"]
Essential Python built-in functions: map, filter, zip, enumerate, sorted, and more.
Functional programming tools for transforming and filtering iterables.
from functools import reduce # map - apply function to each element numbers = [1, 2, 3, 4, 5] doubled = list(map(lambda x: x * 2, numbers)) print(doubled) # [2, 4, 6, 8, 10] # filter - keep elements that pass test evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4] # reduce - cumulative operation product = reduce(lambda a, b: a * b, numbers) print(product) # 120 (factorial of 5)
Combine iterables with zip and get index-value pairs with enumerate.
# zip - combine multiple iterables
names = ["Alice", "Bob", "Charlie"]
ages = [30, 25, 35]
for name, age in zip(names, ages):
print(f"{name}: {age}")
# zip longest (itertools)
from itertools import zip_longest
for n, a in zip_longest(names, [30, 25], fillvalue="N/A"):
print(n, a)
# enumerate - get index and value
for i, name in enumerate(names, start=1):
print(f"{i}. {name}")
# 1. Alice 2. Bob 3. Charlie
Sort any iterable and reverse sequences with built-in functions.
# sorted - returns new sorted list
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_nums = sorted(numbers)
print(sorted_nums) # [1, 1, 2, 3, 4, 5, 9]
# Custom sort key
words = ["banana", "apple", "cherry", "date"]
by_length = sorted(words, key=len)
print(by_length) # ['date', 'apple', 'banana', 'cherry']
# Reverse sorting
reverse_nums = sorted(numbers, reverse=True)
print(reverse_nums) # [9, 5, 4, 3, 2, 1, 1]
# reversed - returns iterator
for num in reversed(range(5)):
print(num, end=" ") # 4 3 2 1 0
Quick aggregation and truth-testing over iterables.
values = [0, 1, 2, 3, 4] # any - True if at least one is truthy print(any(values)) # True (1 is truthy) print(any([0, 0, 0])) # False # all - True if all are truthy print(all(values)) # False (0 is falsy) print(all([1, 2, 3])) # True # min, max, sum print(min(values)) # 0 print(max(values)) # 4 print(sum(values)) # 10 # With custom key words = ["cat", "elephant", "dog"] print(min(words, key=len)) # cat
Copy, paste, and adapt 50+ ready-to-use Python code snippets. From "Hello World" to decorators – we've got you covered.
No signup required. All snippets are free, tested, and work with Python 3.6+.
Bookmark this cheatsheet for quick reference – all snippets are free and always will be.
Get new AI tools, SEO resources, calculators, prompts and free templates delivered to your inbox. No spam, unsubscribe anytime.
By subscribing, you agree to our Privacy Policy. No spam, ever.
Successfully Subscribed!
Thank you for joining the FreeToolr community. Check your inbox for a confirmation email.

FreeToolr is the ultimate platform for free online tools, AI tools, SEO tools, PDF utilities, calculators, image tools and developer resources.
[email protected] Buy Me a Coffee