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 |
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 |
' 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 |
/ 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.
== 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) |
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 |
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) |
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"} |
{} — that's a dict. Use set() for empty set.Conditionals
Branch code based on conditions.
if / elif / else
Ternary (one-liner conditional)
match/case (Python 3.10+)
if, elif, else.Loops
Repeat code. for over items, while on condition.
for loop
range()
enumerate()
zip() — loop multiple lists
while loop
break & continue
else clause (runs if no break)
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
Dict comprehension
Set comprehension
Functions
Reusable blocks of code.
Basic function
Default arguments
*args — variable positional arguments
**kwargs — variable keyword arguments
Type hints
Lambda (anonymous function)
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
Inheritance
@property decorator
Magic methods
| Method | Called when |
|---|---|
__init__ |
Object created |
__str__ |
str(obj) or print(obj) |
__repr__ |
Representation for debugging |
__len__ |
len(obj) |
__eq__ |
obj1 == obj2 |
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
Write file
CSV reading (csv module)
File modes
| Mode | Meaning |
|---|---|
"r" | Read (default) |
"w" | Write (overwrite) |
"a" | Append |
"rb", "wb" | Binary modes |
with open(...) as f: — it auto-closes.Exception Handling
Catch and handle errors gracefully.
try / except / else / finally
Raise custom exception
Common exceptions
| Exception | When |
|---|---|
ValueError | Wrong type/value |
TypeError | Wrong type in operation |
KeyError | Key not in dict |
IndexError | Index out of range |
FileNotFoundError | File doesn't exist |
ZeroDivisionError | Division by zero |
except: catches everything and hides bugs. Use except SpecificError:.Imports & Modules
Reuse code from other files and libraries.
Import entire module
Import specific function
Alias import
Import all (use sparingly)
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
json — parse and write JSON
os & pathlib — work with files and paths
collections — Counter, defaultdict, namedtuple
itertools — efficient iteration
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
❌
def add_item(item, lst=[]):✓
def add_item(item, lst=None): lst = lst or []The list persists across calls — always use None as default.
❌
try: ... except: ...✓
except ValueError:Bare except hides bugs. Always catch specific exceptions.
❌
for x in lst: lst.remove(x)✓
lst = [x for x in lst if condition]Iterator skips items. Use list comprehension instead.
❌
if x == None:✓
if x is None:is checks identity; == checks equality. For None, always use is.
❌
for i in range(len(items)): print(items[i])✓
for i, item in enumerate(items): print(i, item)More Pythonic and readable.
❌
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:
| Cheatsheet Section | Full Lesson | Time |
|---|---|---|
| Variables & Types | Variables & Data Types in Python | 15 min |
| Strings & Formatting | Strings & String Methods | 18 min |
| Numbers & Math | Numbers & Operators in Python | 16 min |
| Lists & Tuples | Lists & Tuples | 19 min |
| Dictionaries | Dictionaries in Python | 17 min |
| Sets | Sets in Python | 14 min |
| Conditionals | How Python Works: Control Flow | 20 min |
| Loops | Loops: for & while | 21 min |
| Comprehensions | List Comprehensions | 16 min |
| Functions | Functions in Python | 22 min |
| Classes | OOP & Classes in Python | 23 min |
| File I/O | File Handling & CSV | 18 min |
| Error Handling | Exception Handling | 17 min |
| Imports | Modules & Imports | 15 min |
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 →