Every essential Python concept in one place — syntax, data types, OOP, comprehensions, file I/O, exceptions, modules, and more. Curated for beginners to advanced developers.
The building blocks — variables, print, comments, input, and type casting.
# Variable assignment — no type declaration name = "Alice" age = 25 pi = 3.14159 is_dev = True # Multiple assignment x, y, z = 1, 2, 3 a = b = c = 0 # Print with f-string (Python 3.6+) print(f"Hello, {name}! Age: {age}") print(f"{name!r}") # repr print(f"{pi:.2f}") # formatted float print("sep", "test", sep="-", end="!\n")
# Type casting int("42") # → 42 float("3.14") # → 3.14 str(100) # → "100" bool(0) # → False list((1,2,3)) # tuple → list tuple([1,2,3]) # list → tuple # Input (always returns string) name = input("Enter name: ") age = int(input("Enter age: ")) # Check type type(name) # <class 'str'> isinstance(age, int) # True
Lists, tuples, sets, dicts, and strings — with the most-used methods.
s = "Hello, Python!" # Slicing [start:stop:step] s[0:5] # "Hello" s[::-1] # reversed # Methods s.upper() # "HELLO, PYTHON!" s.lower() # "hello, python!" s.strip() # remove whitespace s.split(",") # ["Hello", " Python!"] s.replace("Python","World") s.find("Python") # 7 s.startswith("Hello") # True s.count("l") # 3 ",".join(["a","b","c"]) # "a,b,c" len(s) # 14
nums = [3, 1, 4, 1, 5, 9] nums.append(2) # add to end nums.insert(2, 99) # insert at index nums.remove(1) # removes first 1 nums.pop() # removes & returns last nums.pop(0) # removes & returns first nums.sort() # in-place sort nums.sort(reverse=True) nums.reverse() # in-place reverse sorted(nums) # returns new sorted list nums.index(5) # → 4 nums.count(1) # → 2 nums.extend([6,7]) # merge list nums.copy() # shallow copy
d = {"name": "Alice", "age": 25}
d["email"] = "alice@email.com" # add/update
d.get("phone", "N/A") # safe get
d.update({"city": "Delhi"})
del d["age"] # delete key
d.pop("name") # remove & return
d.keys() # dict_keys([...])
d.values() # dict_values([...])
d.items() # dict_items([(k,v)])
# Iterate
for k, v in d.items():
print(k, v)
"name" in d # True
d.setdefault("score", 0)
# Sets — unordered, unique s = {1, 2, 3, 3} # → {1, 2, 3} s.add(4) s.discard(2) s.remove(1) # raises if missing a | b # union a & b # intersection a - b # difference a ^ b # symmetric diff a.issubset(b) # Tuples — immutable t = (1, 2, 3) t[0] # → 1 (access) x, y, z = t # unpack t.count(1) # → 1 t.index(2) # → 1 (1,) + (2,3) # concat
| Op | Example | Result |
|---|---|---|
+ |
5 + 3 |
8 |
- |
5 - 3 |
2 |
* |
5 * 3 |
15 |
/ |
7 / 2 |
3.5 |
// |
7 // 2 |
3 |
% |
7 % 2 |
1 |
** |
2 ** 8 |
256 |
+= |
x += 5 |
x = x+5 |
-= |
x -= 2 |
x = x-2 |
| Op | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal |
> |
Greater than |
< |
Less than |
>= |
Greater or equal |
<= |
Less or equal |
and |
Logical AND |
or |
Logical OR |
not |
Logical NOT |
| Op | Meaning |
|---|---|
is |
Same object |
is not |
Not same object |
in |
Membership test |
not in |
Not in sequence |
& |
Bitwise AND |
| |
Bitwise OR |
^ |
Bitwise XOR |
~ |
Bitwise NOT |
<< >> |
Bit shift |
score = 82 if score >= 90: grade = "A" elif score >= 75: grade = "B" elif score >= 60: grade = "C" else: grade = "F" # Ternary / inline status = "pass" if score >= 60 else "fail" # Walrus operator (3.8+) if n := len([1,2,3]): print(f"List has {n} items") # match-case (3.10+) match grade: case "A": print("Excellent!") case "B": print("Good") case _: print("Keep going")
# for loop for i in range(5): # 0..4 print(i) for i in range(2, 10, 2): # 2,4,6,8 print(i) for idx, val in enumerate(["a","b"]): print(idx, val) for a, b in zip([1,2],[3,4]): print(a, b) # while loop n = 0 while n < 5: n += 1 else: # runs if no break print("done") # Control statements break # exit loop continue # skip iteration pass # no-op placeholder
def greet(name: str, greeting: str = "Hello") -> str: """Return a greeting string.""" return f"{greeting}, {name}!" # *args — variable positional def total(*nums): return sum(nums) # **kwargs — variable keyword def info(**kwargs): for k, v in kwargs.items(): print(f"{k}: {v}") # Unpacking args nums = [1, 2, 3] total(*nums) # → 6 # Return multiple values (tuple) def divmod_custom(a, b): return a // b, a % b q, r = divmod_custom(10, 3)
# Lambda — anonymous single-expression fn square = lambda x: x ** 2 add = lambda a, b: a + b # map — apply fn to all items nums = [1, 2, 3, 4] squares = list(map(lambda x: x**2, nums)) # filter — keep items where fn is True evens = list(filter(lambda x: x%2==0, nums)) # reduce — accumulate to single value from functools import reduce product = reduce(lambda a,b: a*b, nums) # 24 # Sort with key words = ["banana", "apple", "cherry"] words.sort(key=lambda w: len(w)) # Closures def make_multiplier(n): return lambda x: x * n double = make_multiplier(2)
class Animal: species = "Unknown" # class var def __init__(self, name, age): self.name = name # instance var self._age = age # protected def speak(self): return f"{self.name} makes a sound" def __str__(self): # str(obj) return f"Animal({self.name})" def __repr__(self): # repr(obj) return f"Animal({self.name!r})" def __len__(self): # len(obj) return self._age class Dog(Animal): # inheritance species = "Canis" def speak(self): # override return "Woof!" def fetch(self, item): # new method return f"{self.name} fetched {item}" d = Dog("Buddy", 3) isinstance(d, Animal) # True super().__init__(...) # call parent
class Circle: def __init__(self, radius): self._r = radius @property def radius(self): return self._r @radius.setter def radius(self, v): if v < 0: raise ValueError self._r = v @staticmethod def info(): return "A circle" @classmethod def unit(cls): return cls(1) # dataclass (Python 3.7+) from dataclasses import dataclass, field @dataclass class Point: x: float y: float label: str = "origin" tags: list = field(default_factory=list) p = Point(1.0, 2.0) # auto __init__, __repr__
# List comprehension squares = [x**2 for x in range(10)] evens = [x for x in range(20) if x%2==0] flat = [n for row in matrix for n in row] # Dict comprehension sq_map = {x: x**2 for x in range(5)} inverted = {v: k for k,v in sq_map.items()} # Set comprehension unique_sq = {x**2 for x in [-2,-1,0,1,2]} # Nested comprehension matrix = [[1 if r==c else 0 for c in range(3)] for r in range(3)] # identity matrix
# Generator expression (lazy) gen = (x**2 for x in range(1_000_000)) next(gen) # → 0 (no memory overhead) # Generator function def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b fib = fibonacci() [next(fib) for _ in range(8)] # [0,1,1,2,3,5,8,13] # yield from def chain(*iterables): for it in iterables: yield from it # itertools essentials from itertools import islice, chain, product list(islice(fibonacci(), 10))
try: result = 10 / 0 except ZeroDivisionError as e: print(f"Math error: {e}") except (TypeError, ValueError) as e: print(f"Type/Value error: {e}") except Exception as e: print(f"Unexpected: {e}") raise # re-raise else: print("No exception!") # runs if no except finally: print("Always runs") # cleanup # Custom exception class ValidationError(Exception): def __init__(self, field, msg): super().__init__(msg) self.field = field raise ValidationError("email", "Invalid")
| Exception | When raised |
|---|---|
ValueError |
Wrong value type |
TypeError |
Wrong argument type |
IndexError |
Index out of range |
KeyError |
Dict key missing |
AttributeError |
Attribute missing |
NameError |
Variable not defined |
FileNotFoundError |
File missing |
ImportError |
Module not found |
StopIteration |
Iterator exhausted |
RuntimeError |
Generic runtime |
OverflowError |
Arithmetic overflow |
RecursionError |
Max recursion depth |
# Context manager (auto-close) with open("data.txt", "r") as f: content = f.read() # entire file lines = f.readlines() # list of lines line = f.readline() # one line # Write (overwrites) with open("out.txt", "w") as f: f.write("Hello!\n") f.writelines(["line1\n", "line2\n"]) # Append with open("log.txt", "a") as f: f.write("new entry\n") # Binary mode with open("img.png", "rb") as f: data = f.read() # Modes: r w a x rb wb ab r+ w+
from pathlib import Path p = Path("data") / "file.txt" p.exists(); p.is_file(); p.is_dir() p.read_text(); p.write_text("hi") p.mkdir(parents=True, exist_ok=True) list(p.parent.glob("*.txt")) p.suffix; p.stem; p.name # JSON import json data = {"name": "Alice", "age": 25} with open("data.json", "w") as f: json.dump(data, f, indent=2) with open("data.json") as f: loaded = json.load(f) # CSV import csv with open("data.csv", "r") as f: reader = csv.DictReader(f) rows = [row for row in reader]
import math import os as operating_sys from datetime import datetime, date from collections import Counter, defaultdict from typing import List, Dict, Optional from . import sibling_module # relative from ..pkg import something # up a level # Conditional import try: import ujson as json except ImportError: import json # __name__ guard if __name__ == "__main__": main()
from datetime import datetime now = datetime.now() now.strftime("%Y-%m-%d %H:%M:%S") datetime.strptime( "2024-01-15", "%Y-%m-%d" ) datetime.today().year import os os.getcwd() os.listdir(".") os.path.join("data", "file.txt") os.path.exists("path") os.environ.get("HOME") os.makedirs("a/b/c", exist_ok=True) import sys sys.argv # command-line args sys.exit(0) # exit program sys.path # module search path
from collections import Counter, deque, defaultdict, OrderedDict Counter("abracadabra") # {'a':5,...} Counter.most_common(3) dq = deque( [1, 2, 3], maxlen=5 ) dq.appendleft(0) dq.rotate(2) dd = defaultdict(list) dd["key"].append(1) # no KeyError from functools import lru_cache, partial, wraps @lru_cache(maxsize=None) def fib(n): return n if n < 2 else fib(n-1) + fib(n-2) double = partial(pow, exp=2)
Go beyond the cheat sheet. Join our industry-expert-led courses and build real projects.