How to Use This Cheatsheet

This reference covers all core Python syntax from the Ramayai Python track. Each section shows syntax, a quick example, and a common beginner mistake. Use this to look up syntax while coding, refresh concepts between lessons, or prepare for interviews.

💻 Press Cmd+P (Mac) or Ctrl+P (Windows/Linux) to print this page.

Variables & Types

Assign values to names; Python infers type.

Concept Syntax Example
Assign variable name = value age = 25
Check type type(x) type(age) → <class 'int'>
Type cast int(), str(), float(), bool() int("42") → 42
Delete variable del name del age
Swap two vars a, b = b, a x, y = 1, 2; x, y = y, x
❌ Mistake: Using undefined variables. Always assign before use: name = "Aisha" before print(name).

Strings & Formatting

Three ways to format strings: f-strings (modern), .format(), and % operator.

Method Syntax Example
f-string (best) f"text {var}" name = "Arjun"; f"Hello {name}"
.format() "text {}".format(var) "Hello {}".format("Arjun")
% operator "text %s" % var "Hello %s" % "Arjun"
String methods .upper(), .lower(), .strip(), .split() "hello".upper() → "HELLO"
String slicing s[start:end] "Python"[0:3] → "Pyt"
String length len(s) len("Python") → 6
❌ Mistake: Mixing quote types. Use single ' or double " consistently, or escape: "It's working".

Numbers & Math Operations

Integer, float, and arithmetic with operator precedence.

Operator Name Example
+, -, *, / Add, subtract, multiply, divide 5 + 3 → 8; 10 / 2 → 5.0
// Floor divide (integer) 7 // 2 → 3
% Modulo (remainder) 7 % 2 → 1
** Exponent 2 ** 3 → 8
+=, -=, *=, /= Compound operators x += 5 same as x = x + 5
❌ Mistake: Forgetting / returns float. Use // for integer division: 5 // 2 → 2, not 5 / 2 → 2.5.

Booleans & Truthiness

True/False logic and what evaluates as truthy or falsy.

Concept Syntax Example
Comparison ==, !=, <, >, <=, >= 5 > 3 → True; 5 == "5" → False
Logical AND and True and False → False
Logical OR or True or False → True
Logical NOT not not True → False
Identity check is, is not x is None; x is not None
Membership in, not in "a" in "apple" → True

Falsy values: False, None, 0, 0.0, "", [], {}, (). Everything else is truthy.

❌ Mistake: Using == None instead of is None. Use is for identity: if x is None: not if x == None:.

Lists

Ordered, mutable collection of items. Indexed from 0.

Operation Syntax Example
Create list [] or list() items = [1, 2, 3]
Index (0-based) lst[i] items[0] → 1
Slice lst[start:end] items[1:3] → [2, 3]
Negative index lst[-1] items[-1] → last item
Append .append(x) items.append(4)
Extend .extend(list) items.extend([4, 5])
Insert .insert(i, x) items.insert(1, 99)
Remove .remove(x) items.remove(2)
Pop .pop([i]) items.pop() → last; items.pop(0) → first
Index of item .index(x) items.index(2) → position
Count occurrences .count(x) items.count(2)
Sort .sort() items.sort()
Reverse .reverse() items.reverse()
Length len(lst) len(items)
❌ Mistake: Modifying a list while iterating: for x in lst: lst.remove(x). Use list comprehension or slice instead.

Tuples

Ordered, immutable collection. Once created, cannot change.

Operation Syntax Example
Create () or tuple() point = (1, 2, 3)
Single item (x,) note comma single = (42,)
Index & slice t[i], t[start:end] point[0] → 1; point[1:] → (2, 3)
Unpack a, b, c = tuple x, y, z = point
Length/count len(t), t.count(x) len(point) → 3
❌ Mistake: Trying to modify: t[0] = 5 raises TypeError. Tuples are immutable. Create a new tuple instead.

Dictionaries

Key-value pairs. Keys must be unique; unordered (ordered in Python 3.7+).

Operation Syntax Example
Create {"key": value} or dict() user = {"name": "Aisha", "age": 28}
Access d[key] user["name"] → "Aisha"
Get with default .get(key, default) user.get("email", "N/A")
Set value d[key] = value user["age"] = 29
Delete del d[key] del user["age"]
Check key exists key in d "name" in user → True
Keys, values, items .keys(), .values(), .items() user.keys() → ["name", "age"]
Pop with default .pop(key, default) user.pop("age", 0)
Set default .setdefault(key, val) user.setdefault("city", "Nairobi")
Update .update(dict) user.update({"age": 30})
Length len(d) len(user)
❌ Mistake: Using d["key"] when key doesn't exist raises KeyError. Use .get() instead: d.get("missing", default_value).

Sets

Unordered, unique items. No duplicates or indexing.

Operation Syntax Example
Create {1, 2, 3} or set() tags = {"python", "code", "ai"}
Add item .add(x) tags.add("data")
Remove .remove(x) tags.remove("code")
Discard (safe) .discard(x) tags.discard("missing") no error
Union s1 | s2 {"a"} | {"b"} → {"a", "b"}
Intersection s1 & s2 {"a", "b"} & {"b", "c"} → {"b"}
Difference s1 - s2 {"a", "b"} - {"b"} → {"a"}
Symmetric diff s1 ^ s2 {"a", "b"} ^ {"b", "c"} → {"a", "c"}
❌ Mistake: Creating empty set with {} — that's a dict. Use set() for empty set.

Conditionals

Branch code based on conditions.

if / elif / else

Python

Ternary (one-liner conditional)

Python

match/case (Python 3.10+)

Python
❌ Mistake: Forgetting indentation. Python requires 4-space indent after if, elif, else.

Loops

Repeat code. for over items, while on condition.

for loop

Python

range()

Python

enumerate()

Python

zip() — loop multiple lists

Python

while loop

Python

break & continue

Python

else clause (runs if no break)

Python
❌ Mistake: Using range(len(x)) when you can use enumerate(x) or just for item in x.

List / Dict / Set Comprehensions

Compact way to create lists, dicts, and sets from loops.

List comprehension

Square numbers
With condition
Transform

Dict comprehension

Python

Set comprehension

Python
❌ Mistake: Overly complex comprehensions. Keep them readable: one condition, one transformation. Use a loop if it needs multiple lines.

Functions

Reusable blocks of code.

Basic function

Python

Default arguments

Python

*args — variable positional arguments

Python

**kwargs — variable keyword arguments

Python

Type hints

Python

Lambda (anonymous function)

Python
❌ Mistake: Mutable default arguments: def add_item(item, lst=[]). List persists across calls. Use lst=None and create inside function.

Classes & Objects

Blueprint for objects. Methods are functions inside a class.

Basic class

Python

Inheritance

Python

@property decorator

Python

Magic methods

Method Called when
__init__ Object created
__str__ str(obj) or print(obj)
__repr__ Representation for debugging
__len__ len(obj)
__eq__ obj1 == obj2
❌ Mistake: Forgetting self in methods. First parameter is always self: def method(self, x).

File I/O

Read and write files safely with context manager.

Read file

Python

Write file

Python

CSV reading (csv module)

Python

File modes

ModeMeaning
"r"Read (default)
"w"Write (overwrite)
"a"Append
"rb", "wb"Binary modes
❌ Mistake: Not closing files. Always use with open(...) as f: — it auto-closes.

Exception Handling

Catch and handle errors gracefully.

try / except / else / finally

Python

Raise custom exception

Python

Common exceptions

ExceptionWhen
ValueErrorWrong type/value
TypeErrorWrong type in operation
KeyErrorKey not in dict
IndexErrorIndex out of range
FileNotFoundErrorFile doesn't exist
ZeroDivisionErrorDivision by zero
❌ Mistake: Using bare except: catches everything and hides bugs. Use except SpecificError:.

Imports & Modules

Reuse code from other files and libraries.

Import entire module

Python

Import specific function

Python

Alias import

Python

Import all (use sparingly)

Python
❌ Mistake: Using from x import * — unclear what's imported and causes name collisions.

Standard Library Quick Hits

Five essential modules for everyday Python.

datetime — work with dates & times

Python

json — parse and write JSON

Python

os & pathlib — work with files and paths

Python

collections — Counter, defaultdict, namedtuple

Python

itertools — efficient iteration

Python

Common Idioms & Patterns

Swap two variables

Flatten list of lists

Create dict from two lists

Count occurrences (Counter)

Group items by key

Ternary conditional

❌ Anti-Patterns: 6 Mistakes to Avoid

Mutable default arguments
❌ def add_item(item, lst=[]):
✓ def add_item(item, lst=None): lst = lst or []
The list persists across calls — always use None as default.
Bare except clause
❌ try: ... except: ...
✓ except ValueError:
Bare except hides bugs. Always catch specific exceptions.
Modifying list while iterating
❌ for x in lst: lst.remove(x)
✓ lst = [x for x in lst if condition]
Iterator skips items. Use list comprehension instead.
Using == None instead of is None
❌ if x == None:
✓ if x is None:
is checks identity; == checks equality. For None, always use is.
range(len(x)) instead of enumerate or direct iteration
❌ for i in range(len(items)): print(items[i])
✓ for i, item in enumerate(items): print(i, item)
More Pythonic and readable.
Manual indexing instead of zip
❌ for i in range(len(a)): print(a[i], b[i])
✓ for x, y in zip(a, b): print(x, y)
zip handles length mismatches gracefully.

Where to Learn Each Topic

Each cheatsheet section maps to a full lesson in the Ramayai Python track:

Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

Ready to go further?

Join the Best AI Program: The AI-Era Analyst — 5 months, fully online, with placement assistance. Week 1 is free.

Explore The AI-Era Analyst →