Python · Quick Reference

🐍 Python Cheat Sheet – Complete Reference

Data types · operators · control flow · data structures · functions · modules · best practices – all in one page. Click any section in the sidebar to jump, search to filter, or save as PDF.

📦 1. Data Types
TypeExampleDescription
int10Integer
float10.5Floating point
str'hello'String
boolTrue / FalseBoolean
list[1, 2, 3]Mutable sequence
tuple(1, 2, 3)Immutable sequence
dict{'a': 1, 'b': 2}Key-value mapping
set{1, 2, 3}Unique unordered
NoneTypeNoneNull / absence
🧮 2. Operators
Arithmetic & Comparison
# Arithmetic
10 + 3   # 13
10 - 3   # 7
10 * 3   # 30
10 / 3   # 3.333...
10 // 3  # 3  (floor division)
10 % 3   # 1  (modulus)
2 ** 4   # 16 (exponent)

# Comparison
a == b   # equal
a != b   # not equal
a > b    # greater than
a < b    # less than
a >= b   # greater or equal
a <= b   # less or equal

Logical: and, or, not   |   Assignment: =, +=, -=, *=, etc.

🎮 3. Control Flow
if / elif / else
if condition:
    statement
elif other_condition:
    statement
else:
    statement
while & for loops
while condition:
    statement

for item in iterable:
    statement

# for ... else (executes if no break)
for item in items:
    if found: break
else:
    print("Completed without break")
🗂️ 4. Data Structures
List
lst = [1, 2, 3]
lst.append(4)       # [1,2,3,4]
lst[0] = 10
lst[-1]             # last element
lst[1:3] = [8,9]    # slice assignment
Tuple
t = (1, 2, 3)
t[0]          # access
t.count(2)    # 1
t.index(3)    # 2
Set
s = {1, 2, 3}
s.add(4)
s.remove(2)
2 in s        # False
Dictionary
d = {'a': 1, 'b': 2}
d['a'] = 1
d['c'] = 3
d.keys()      # dict_keys(['a','b','c'])
d.values()    # dict_values([1,2,3])
d.items()     # [('a',1),('b',2),('c',3)]
⚙️ 5. Functions
Basic & default arguments
def greet(name='User'):
    return f"Hello, {name}!"

def my_func(a, b):
    """Docstring example"""
    return a + b
*args and **kwargs
def func(*args, **kwargs):
    print(args)   # tuple
    print(kwargs) # dict

func(1, 2, lang="Python", version=3)
🔤 6. String Methods
s = "  Hello, World!  "
s.upper()            # '  HELLO, WORLD!  '
s.lower()            # '  hello, world!  '
s.strip()            # 'Hello, World!'
s.replace('l','x')   # '  Hexxo, Worxd!  '
s.split(', ')        # ['  Hello', 'World!  ']
'-'.join(['a','b'])  # 'a-b'
s.find('o')          # 6
s.count('l')         # 3
✨ 7. List Comprehension
squares = [x**2 for x in range(5)]          # [0,1,4,9,16]
even_numbers = [x for x in range(10) if x % 2 == 0]  # [0,2,4,6,8]
matrix = [[i*j for i in range(3)] for j in range(3)]
# [[0,0,0],[0,1,2],[0,2,4]]
📁 8. File I/O
Read / Write / Append
# Read
with open('file.txt', 'r') as f:
    data = f.read()

# Write (overwrites)
with open('file.txt', 'w') as f:
    f.write('Hello World')

# Append
with open('file.txt', 'a') as f:
    f.write('\nNew Line')
⚠️ 9. Exception Handling
try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    print("Error:", e)
else:
    print("No Exception")
finally:
    print("Always executed")
📦 10. Common Modules
import math, random, datetime, os, json
math.sqrt(16)                # 4.0
math.pi
random.randint(1,10)
datetime.datetime.now().strftime('%Y-%m-%d')
os.getcwd()
os.path.exists('file.txt')
json_str = json.dumps({'key':'value'})
data = json.loads(json_str)
math.factorial(5) → 120 random.choice([1,2,3]) datetime.now() os.listdir('.')
🔧 11. Built‑in Functions
print() len() type() input() sum() max() min() sorted() range() enumerate() abs() round() zip() map() filter() any() all() open()
enumerate & zip example
for idx, val in enumerate(['a','b','c']):
    print(idx, val)
pairs = list(zip([1,2], ['x','y']))   # [(1,'x'),(2,'y')]
⚡ 12. Lambda · Map · Filter · Reduce
add = lambda a, b: a + b
print(add(2, 3))   # 5

from functools import reduce
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, nums))   # [1,4,9,16,25]
evens = list(filter(lambda x: x%2==0, nums)) # [2,4]
total = reduce(lambda x,y: x+y, nums)        # 15
💡 13. Useful Tips
✅ Python is case sensitive (myVar vs myvar).
✅ Use meaningful variable names.
✅ Use list/dict/set comprehensions for cleaner code.
✅ Handle exceptions gracefully – avoid bare except.
✅ Use virtual environments: python -m venv env.
✅ Readability counts! Follow PEP 8.
📌 14. Version Check & Docstring
Python version
import sys
print(sys.version)
Docstring example
def func():
    """This is a docstring.
    It describes the function.
    """
    pass

print(func.__doc__)
📖 Access docstring: help(func) or func.__doc__
😕 No cheat sheet items match your search. Try a different keyword.