Python Quick Reference
A printable, at-a-glance reference for Python 3. Covers the essentials — perfect for coding interviews, exam prep, or daily use.
Syntax Basics
# Single-line comment
""" Multi-line
comment """
# Variable assignment (no type declaration needed)
x = 5 # int
y = 3.14 # float
name = "Alice" # str
# Printing
print("Hello") # with newline
print("No newline", end="") # without newline
print(f"Value is {x}") # f-string interpolation
Data Types
| Type | Example | Mutable | Notes |
|---|---|---|---|
int | x = 42 | No | Arbitrary precision |
float | x = 3.14 | No | Double-precision |
str | s = "hello" | No | Immutable sequence of chars |
bool | b = True | No | Subclass of int |
NoneType | x = None | No | Represents absence of value |
list | lst = [1, 2, 3] | Yes | Ordered, indexed, allows duplicates |
tuple | t = (1, 2, 3) | No | Ordered, immutable |
dict | d = {"a": 1} | Yes | Key-value pairs (3.7+ preserves order) |
set | s = {1, 2, 3} | Yes | Unordered, no duplicates |
Operators
Arithmetic
| Operator | Description | Example |
|---|---|---|
+ | Addition | 5 + 3 → 8 |
- | Subtraction | 5 - 3 → 2 |
* | Multiplication | 5 * 3 → 15 |
/ | Division (float) | 5 / 2 → 2.5 |
// | Floor division | 5 // 2 → 2 |
% | Modulus | 5 % 2 → 1 |
** | Exponentiation | 5 ** 2 → 25 |
Comparison
| Operator | Description | Example |
|---|---|---|
== | Equal to | 5 == 5 → True |
!= | Not equal to | 5 != 3 → True |
> | Greater than | 5 > 3 → True |
< | Less than | 5 < 3 → False |
>= | Greater than or equal | 5 >= 5 → True |
<= | Less than or equal | 5 <= 3 → False |
Logical
| Operator | Description | Example |
|---|---|---|
and | Both True | True and False → False |
or | At least one True | True or False → True |
not | Inverts truth value | not True → False |
Assignment
| Operator | Example | Equivalent to |
|---|---|---|
= | x = 5 | — |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
//= | x //= 3 | x = x // 3 |
%= | x %= 3 | x = x % 3 |
**= | x **= 3 | x = x ** 3 |
Membership & Identity
| Operator | Description | Example |
|---|---|---|
in | Is element in sequence? | "a" in "cat" → True |
not in | Is element not in sequence? | "z" not in "cat" → True |
is | Same object identity? | x is None |
is not | Different object identity? | x is not None |
String Methods
| Method | Description | Example |
|---|---|---|
.upper() | Convert to uppercase | "hi".upper() → "HI" |
.lower() | Convert to lowercase | "HI".lower() → "hi" |
.split(sep) | Split by delimiter into list | "a,b,c".split(",") → ["a","b","c"] |
.join(iterable) | Join elements with string | ",".join(["a","b"]) → "a,b" |
.replace(old, new) | Replace occurrences | "hi".replace("i","ello") → "hello" |
.strip() | Remove leading/trailing whitespace | " hi ".strip() → "hi" |
.find(sub) | Index of first occurrence | "hello".find("l") → 2 |
.startswith(prefix) | Check prefix | "hi".startswith("h") → True |
.endswith(suffix) | Check suffix | "hi".endswith("i") → True |
.count(sub) | Count non-overlapping occurrences | "lol".count("l") → 2 |
List Methods
| Method | Description | Example |
|---|---|---|
.append(x) | Add x to end | [1].append(2) → [1, 2] |
.extend(iter) | Append all from iterable | [1].extend([2,3]) → [1,2,3] |
.insert(i, x) | Insert x at index i | [1,3].insert(1,2) → [1,2,3] |
.remove(x) | Remove first occurrence of x | [1,2,1].remove(1) → [2,1] |
.pop(i) | Remove & return item at i (default last) | [1,2,3].pop() → 3 |
.sort() | Sort in-place | [3,1,2].sort() → [1,2,3] |
.reverse() | Reverse in-place | [1,2,3].reverse() → [3,2,1] |
.index(x) | Index of first occurrence | [1,2,3].index(2) → 1 |
.count(x) | Count occurrences | [1,2,2].count(2) → 2 |
.copy() | Shallow copy | lst.copy() |
List slicing: lst[start:stop:step] — [1,2,3,4][1:3] → [2,3]
Dictionary Methods
| Method | Description | Example |
|---|---|---|
.keys() | View of all keys | d.keys() |
.values() | View of all values | d.values() |
.items() | View of (key, value) pairs | d.items() |
.get(k, default) | Safe lookup | d.get("x", 0) → 0 |
.update(d2) | Merge from another dict | d.update({"b": 2}) |
.pop(k, default) | Remove & return value | d.pop("a") |
.setdefault(k, v) | Set default if key missing | d.setdefault("a", 0) |
.clear() | Remove all items | d.clear() |
Control Flow
if-elif-else
if condition:
# do something
elif other_condition:
# do something else
else:
# fallback
for Loop
for item in iterable:
# process item
for i in range(5): # 0, 1, 2, 3, 4
for i in range(2, 6): # 2, 3, 4, 5
for i in range(1, 10, 2): # 1, 3, 5, 7, 9
while Loop
while condition:
# repeat while condition is True
Loop Control
break # exit loop immediately
continue # skip to next iteration
else: # runs if loop didn't break
Functions
def
def function_name(param1, param2="default"):
"""Docstring"""
result = param1 + param2
return result
*args / **kwargs
def func(*args, **kwargs):
# args → tuple of positional arguments
# kwargs → dict of keyword arguments
lambda
lambda x: x * 2 # single expression, implicit return
lambda a, b: a + b
# Usage
sorted(list, key=lambda x: x[1])
map(lambda x: x * 2, [1, 2, 3])
return
return value # exit and return value
return # exit and return None
# No return → function returns None
List Comprehension
# Basic
[x * 2 for x in range(5)] # → [0, 2, 4, 6, 8]
# With condition
[x for x in range(10) if x % 2 == 0] # → [0, 2, 4, 6, 8]
# Nested
[(x, y) for x in [1,2] for y in [3,4]]
# Dict comprehension
{k: v for k, v in zip(keys, values)}
# Set comprehension
{x**2 for x in [1, 2, 2, 3]} # → {1, 4, 9}
Classes & OOP
class Parent:
def __init__(self, name):
self.name = name # instance attribute
def greet(self): # instance method
return f"Hi, {self.name}"
class Child(Parent): # inheritance
def __init__(self, name, age):
super().__init__(name) # call parent constructor
self.age = age
def greet(self): # method override
return f"Hey, {self.name} ({self.age})"
# Usage
obj = Child("Alice", 10)
print(obj.greet()) # Hey, Alice (10)
@property
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def area(self):
return 3.14 * self._radius ** 2
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
Access Modifiers (Convention)
self.public # accessible everywhere
self._protected # "internal use" (convention)
self.__private # name-mangled to _ClassName__private
File I/O
# Read entire file
with open("file.txt", "r") as f:
content = f.read()
# Read line by line
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
# Write (overwrite)
with open("file.txt", "w") as f:
f.write("Hello, World!")
# Append
with open("file.txt", "a") as f:
f.write("\nMore text")
# Read all lines into list
with open("file.txt", "r") as f:
lines = f.readlines()
File Modes
| Mode | Description |
|---|---|
"r" | Read (default) |
"w" | Write (overwrites) |
"a" | Append |
"x" | Exclusive creation (fails if exists) |
"r+" | Read + write |
"b" | Binary mode (e.g., "rb", "wb") |
Exception Handling
try:
# code that may raise an exception
result = risky_operation()
except ValueError as e:
# handle specific exception
print(f"Value error: {e}")
except (TypeError, ZeroDivisionError) as e:
# handle multiple exception types
print(f"Error: {e}")
except Exception as e:
# catch-all (use sparingly)
print(f"Unexpected error: {e}")
else:
# runs if no exception was raised
print("Success!")
finally:
# always runs (cleanup)
cleanup()
# Manually raising
raise ValueError("Invalid value")
raise # re-raise current exception
Common Exception Types
| Exception | Raised When |
|---|---|
ValueError | Function receives invalid argument value |
TypeError | Operation on inappropriate type |
IndexError | Sequence subscript out of range |
KeyError | Dictionary key not found |
FileNotFoundError | File does not exist |
ZeroDivisionError | Division by zero |
AttributeError | Attribute reference fails |
ImportError | Import fails |
StopIteration | Iterator exhausted |
Common Built-in Functions
| Function | Description | Example |
|---|---|---|
print(x) | Print to console | print("hi") |
len(x) | Length of sequence | len([1,2,3]) → 3 |
type(x) | Type of object | type(5) → <class 'int'> |
range(n) | Generate integer sequence | list(range(3)) → [0,1,2] |
input(prompt) | Read user input as string | name = input("Name: ") |
int(x) | Convert to integer | int("5") → 5 |
str(x) | Convert to string | str(5) → "5" |
float(x) | Convert to float | float("3.14") → 3.14 |
list(x) | Convert to list | list("abc") → ["a","b","c"] |
dict(x) | Convert to dict | dict([("a",1)]) → {"a":1} |
set(x) | Convert to set | set([1,2,2]) → {1,2} |
sorted(x) | Return sorted list | sorted([3,1,2]) → [1,2,3] |
enumerate(x) | Indexed pairs | list(enumerate(["a","b"])) → [(0,"a"),(1,"b")] |
zip(a, b) | Parallel iteration | list(zip([1,2], ["a","b"])) → [(1,"a"),(2,"b")] |
map(f, x) | Apply function to each | list(map(str, [1,2])) → ["1","2"] |
filter(f, x) | Filter by predicate | list(filter(None, [0,1,0])) → [1] |
abs(x) | Absolute value | abs(-5) → 5 |
sum(x) | Sum of iterable | sum([1,2,3]) → 6 |
min(x) | Minimum value | min([3,1,2]) → 1 |
max(x) | Maximum value | max([3,1,2]) → 3 |
round(x, n) | Round to n decimal places | round(3.14159, 2) → 3.14 |
any(x) | Any element truthy? | any([False, True]) → True |
all(x) | All elements truthy? | all([True, False]) → False |
Module Imports
import math # import entire module
import math as m # with alias
from math import sqrt # import specific name
from math import * # import all (avoid)
from math import sqrt as s # with alias
# Common standard library modules
import os # operating system interface
import sys # system-specific parameters
import json # JSON encoder/decoder
import csv # CSV file reading/writing
import re # regular expressions
import datetime # date and time
import random # random number generation
import math # mathematical functions
import statistics # statistical functions
__name__ Guard
if __name__ == "__main__":
# runs only when script is executed directly
main()