Skip to main content

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

TypeExampleMutableNotes
intx = 42NoArbitrary precision
floatx = 3.14NoDouble-precision
strs = "hello"NoImmutable sequence of chars
boolb = TrueNoSubclass of int
NoneTypex = NoneNoRepresents absence of value
listlst = [1, 2, 3]YesOrdered, indexed, allows duplicates
tuplet = (1, 2, 3)NoOrdered, immutable
dictd = {"a": 1}YesKey-value pairs (3.7+ preserves order)
sets = {1, 2, 3}YesUnordered, no duplicates

Operators

Arithmetic

OperatorDescriptionExample
+Addition5 + 3 → 8
-Subtraction5 - 3 → 2
*Multiplication5 * 3 → 15
/Division (float)5 / 2 → 2.5
//Floor division5 // 2 → 2
%Modulus5 % 2 → 1
**Exponentiation5 ** 2 → 25

Comparison

OperatorDescriptionExample
==Equal to5 == 5 → True
!=Not equal to5 != 3 → True
>Greater than5 > 3 → True
<Less than5 < 3 → False
>=Greater than or equal5 >= 5 → True
<=Less than or equal5 <= 3 → False

Logical

OperatorDescriptionExample
andBoth TrueTrue and False → False
orAt least one TrueTrue or False → True
notInverts truth valuenot True → False

Assignment

OperatorExampleEquivalent to
=x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
//=x //= 3x = x // 3
%=x %= 3x = x % 3
**=x **= 3x = x ** 3

Membership & Identity

OperatorDescriptionExample
inIs element in sequence?"a" in "cat" → True
not inIs element not in sequence?"z" not in "cat" → True
isSame object identity?x is None
is notDifferent object identity?x is not None

String Methods

MethodDescriptionExample
.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

MethodDescriptionExample
.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 copylst.copy()

List slicing: lst[start:stop:step][1,2,3,4][1:3] → [2,3]


Dictionary Methods

MethodDescriptionExample
.keys()View of all keysd.keys()
.values()View of all valuesd.values()
.items()View of (key, value) pairsd.items()
.get(k, default)Safe lookupd.get("x", 0) → 0
.update(d2)Merge from another dictd.update({"b": 2})
.pop(k, default)Remove & return valued.pop("a")
.setdefault(k, v)Set default if key missingd.setdefault("a", 0)
.clear()Remove all itemsd.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

ModeDescription
"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

ExceptionRaised When
ValueErrorFunction receives invalid argument value
TypeErrorOperation on inappropriate type
IndexErrorSequence subscript out of range
KeyErrorDictionary key not found
FileNotFoundErrorFile does not exist
ZeroDivisionErrorDivision by zero
AttributeErrorAttribute reference fails
ImportErrorImport fails
StopIterationIterator exhausted

Common Built-in Functions

FunctionDescriptionExample
print(x)Print to consoleprint("hi")
len(x)Length of sequencelen([1,2,3]) → 3
type(x)Type of objecttype(5) → <class 'int'>
range(n)Generate integer sequencelist(range(3)) → [0,1,2]
input(prompt)Read user input as stringname = input("Name: ")
int(x)Convert to integerint("5") → 5
str(x)Convert to stringstr(5) → "5"
float(x)Convert to floatfloat("3.14") → 3.14
list(x)Convert to listlist("abc") → ["a","b","c"]
dict(x)Convert to dictdict([("a",1)]) → {"a":1}
set(x)Convert to setset([1,2,2]) → {1,2}
sorted(x)Return sorted listsorted([3,1,2]) → [1,2,3]
enumerate(x)Indexed pairslist(enumerate(["a","b"])) → [(0,"a"),(1,"b")]
zip(a, b)Parallel iterationlist(zip([1,2], ["a","b"])) → [(1,"a"),(2,"b")]
map(f, x)Apply function to eachlist(map(str, [1,2])) → ["1","2"]
filter(f, x)Filter by predicatelist(filter(None, [0,1,0])) → [1]
abs(x)Absolute valueabs(-5) → 5
sum(x)Sum of iterablesum([1,2,3]) → 6
min(x)Minimum valuemin([3,1,2]) → 1
max(x)Maximum valuemax([3,1,2]) → 3
round(x, n)Round to n decimal placesround(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()