Skip to content

Python Cheat Sheet

A quick reference for everything taught in this course. For the full explanation of any item, open its section.

Print, comments, variables
print("Hello")                 # show text
print("a", "b", sep="-", end="!")   # a-b!
# this is a comment            # notes for people; Python ignores them
name = "Kalyan"                # a variable: name = value
age = 30                       # reassign any time; snake_case names

Data types and conversion (Section 02)

Data types and conversion
text = "hi"     # str        number = 7      # int
price = 2.5     # float      ok = True       # bool
type(price)                  # <class 'float'>
int("10")  float("2.5")  str(7)   # convert between types
age = int(input("Age: "))    # input() always returns a str

Strings and f-strings (Section 03)

Strings and f-strings
s = "Python"
len(s)            # 6
s.upper()  s.lower()  s.strip()  s.replace("Py", "My")
s.split(",")      # text -> list      ",".join(["a", "b"])  # list -> text
f"Hi {name}, you are {age}"        # f-string
f"{price:.2f}"  f"{1234567:,}"      # 2.50  /  1,234,567
s[0]   s[-1]   s[0:3]   s[::-1]     # index + slice

Operators, booleans, conditionals (Section 04)

Operators, booleans, conditionals
+  -  *  /        # / always gives a float
//  %  **         # floor div, remainder, power
==  !=  <  >  <=  >=        # comparisons -> True/False
and  or  not               # combine booleans
x in items      x not in items      # membership
value is None                       # use is only with None/True/False
if marks >= 90:
    print("A")
elif marks >= 50:
    print("Pass")
else:
    print("Fail")
label = "adult" if age >= 18 else "minor"   # one-line ternary

Collections (Section 05)

Collections
nums = [1, 2, 3]            # list  - ordered, changeable
nums.append(4)  nums.pop()  nums[0]  len(nums)
point = (10, 20)           # tuple - ordered, fixed
person = {"name": "Kalyan", "age": 30}   # dict - key/value
person["name"]   person.get("city")     # .get avoids KeyError
tags = {"a", "b", "a"}     # set   - unique items -> {"a", "b"}

Loops and comprehensions (Section 06)

Loops and comprehensions
while count < 3:           # repeat while a condition holds
    count += 1
for item in items:         # loop over a collection
    print(item)
for i in range(5):         # 0..4      range(2, 10, 2) -> 2,4,6,8
for i, item in enumerate(items):   # index + item
break        # leave the loop      continue   # skip to next
squares = [n * n for n in range(5)]            # list comprehension
evens = [n for n in nums if n % 2 == 0]        # with a filter

Functions (Section 07)

Functions
def greet(name, greeting="Hi"):    # default argument
    """A docstring describes the function."""
    return f"{greeting}, {name}"   # return hands a value back
greet("Kalyan")                    # call it
def total(*args):          # *args  -> tuple of extra positionals
def config(**kwargs):      # **kwargs -> dict of named values
square = lambda x: x * x   # a tiny one-line function

Type hints (Section 08)

Type hints
def add(a: int, b: int) -> int:    # hints are labels, not enforced
    return a + b
name: str = "Kalyan"
scores: list[int] = [90, 85]
city: str | None = None            # optional value

Error handling (Section 09)

Error handling
try:
    n = int(input("Number: "))
except ValueError:                 # catch the specific error
    print("Not a number")
finally:
    print("always runs")
raise ValueError("bad input")      # raise your own error

Files, JSON, paths (Section 10)

Files, JSON, paths
from pathlib import Path
import json
Path("note.txt").write_text("hi")          # write whole file
Path("note.txt").read_text()               # read whole file
with open("data.txt") as f:                # the safe way
    text = f.read()
json.dump(data, open("d.json", "w"), indent=2)   # save JSON
data = json.load(open("d.json"))                  # load JSON
p = Path("reports") / "2026" / "sales.csv"        # build a path
p.name  p.suffix  p.stem  p.parent  p.exists()

Standard library (Section 11)

Standard library
import math
math.pi   math.sqrt(16)   math.ceil(2.1)   math.floor(2.9)
import random
random.seed(3)            # repeatable results
random.randint(1, 6)   random.choice(items)   random.shuffle(items)
from datetime import date, datetime
date.today()   datetime.now()
from collections import Counter
Counter(["a", "b", "a"])   # Counter({"a": 2, "b": 1}) - never raises KeyError

Classes and OOP (Section 13)

Classes and OOP
class Expense:
    def __init__(self, amount, category):   # self = this object
        self.amount = amount
        self.category = category
    def show(self):                         # a method
        return f"{self.category}: {self.amount}"
e = Expense(50, "food")     # create an object
e.amount   e.show()

from dataclasses import dataclass
@dataclass                  # generates __init__ + a clean display
class Point:
    x: int
    y: int

Need a term defined? See the Glossary. New here? Read Start Here first.