

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


















Chapters 1–23 · Compiled study notes
**Table of Contents
1 Getting Started 13 Comprehensions 2 Variables & Data Types 14 Modules & Packages 3 Operators 15 File Handling 4 Strings 16 Exception Handling 5 Input & Output 17 OOP: Classes & Objects 6 Control Flow 18 OOP: Inheritance & Polymorphism 7 Loops 19 Magic / Dunder Methods 8 Lists 20 Iterators & Generators 9 Tuples & Sets 21 Decorators 10 Dictionaries 22 Useful Standard Library 11 Functions 23 venv, pip & Cheat Sheet 12 *args, **kwargs & Scope How to use this notebook:How to use this notebook: yellow boxes are tips, pink boxes are warnings/gotchas, blue "sticky notes" are quick facts, and dark boxes are runnable code with green output underneath.
Variables & Data Types
name = "Ada" age = 28 height = 1. is_coder = True
Type Example Notes int 42 whole numbers, unlimited size float 3.14 decimal numbers str "hi" text, immutable bool True / False subclass of int (True==1) list [1, 2, 3] ordered, mutable tuple (1, 2, 3) ordered, immutable dict {"a": 1} key-value pairs set {1, 2, 3} unordered, unique items NoneType None represents "nothing"
type(age) # str(age) # "28" int("28") # 28 float("3.14") # 3. bool(0), bool(1) # False, True
x, y, z = 1, 2, 3 a = b = c = 0 Tip:Tip: everything in Python is an object -- even functions and classes.
Operators
Op Meaning Example
age = 20 is_member = True age >= 18 and is_member # True
a = [1, 2] b = [1, 2] a == b # True (same values) a is b # False (different objects in memory) Gotcha:Gotcha: use == to compare values, is to compare identity (mainly used for None : x is None ).
"a" in "cat" # True 3 not in [1, 2, 3] # False Operator precedence follows math rules: ******** > *** / // %* / // %** > + -+ - > comparisons > notnot > andand > oror. Use parentheses when unsure!
Input & Output
print("a", "b", sep="-", end="!\n") # a-b!
name = input("What's your name? ") age = int(input("Age? "))
pi = 3. f"{pi:.2f}" # '3.14' f"{1000000:,}" # '1,000,000' f"{7:03d}" # '007' Tip:Tip: for quick debugging, print(f"{variable=}")^ shows both name and value.
Control Flow
age = 20 if age < 13: print("child") elif age < 20: print("teen") else: print("adult")
status = "adult" if age >= 18 else "minor"
items = [] if not items: print("list is empty")
match command: case "start": print("starting") case "stop": print("stopping") case _: print("unknown") Gotcha:Gotcha: don't confuse = (assignment) with == (comparison) inside conditions.
Lists
nums = [3, 1, 4, 1, 5] nums[0] # 3 nums[-1] # 5 nums[1:3] # [1, 4] len(nums) # 5
Method Effect .append(x) add to end .insert(i, x) insert at index .remove(x) remove first match .pop(i) remove & return item at i (default last) .sort() sort in place .reverse() reverse in place .extend(other) append all items from another list
sorted(nums) # new sorted list sum(nums), min(nums), max(nums) list(reversed(nums))
a = [1, 2, 3] b = a # SAME list -- changes to b affect a c = a.copy() # independent shallow copy d = a[:] # also a copy Gotcha:Gotcha: a shallow copy doesn't clone nested lists/dicts inside it -- use copy.deepcopy() for that.
grid = [[1, 2], [3, 4]] grid[1][0] # 3
Tuples & Sets
point = (3, 4) x, y = point # unpacking single = (5,) # trailing comma required for 1-item tuple!
s = {1, 2, 2, 3} # {1, 2, 3} s.add(4) s.remove(1) 3 in s # True (fast lookup)
a = {1, 2, 3} b = {2, 3, 4} a | b # union: {1,2,3,4} a & b # intersection: {2,3} a - b # difference: {1} a ^ b # symmetric diff: {1,4} Tip:Tip: convert a list to a set to remove duplicates fast:^ list(set(my_list))^ (note: order isn't preserved).
Functions
def greet(name): return f"Hello, {name}!" greet("Ada") # 'Hello, Ada!'
def power(base, exp=2): return base ** exp power(3) # 9 (uses default exp) power(3, 3) # 27 power(exp=3, base=2) # 8 (order doesn't matter w/ keywords)
def divmod_custom(a, b): return a // b, a % b # returns a tuple q, r = divmod_custom(7, 2)
def add(a, b): """Return the sum of a and b.""" return a + b
def add(a: int, b: int) -> int: return a + b Gotcha:Gotcha: type hints are NOT enforced at runtime -- they're documentation for humans & tools like mypy. Tip:Tip: a function with no return implicitly returns^ None^.
***args, kwargs & Scope
def total(*nums): return sum(nums) total(1, 2, 3) # 6 -- nums is a tuple (1,2,3)
def profile(**info): for k, v in info.items(): print(k, v) profile(name="Ada", age=28) # info is a dict
nums = [1, 2, 3] total(nums) # unpack list into positional args info = {"name": "Ada"} profile(*info) # unpack dict into keyword args
x = 10 def show(): print(x) # reads global x -- fine def change(): global x x = 20 # need 'global' to MODIFY it Gotcha:Gotcha: a variable assigned anywhere inside a function is treated as local for the whole function unless declared global -- this can cause "referenced before assignment" errors.
def make_multiplier(n): def multiply(x): return x * n # remembers 'n' from outer scope return multiply double = make_multiplier(2) double(5) # 10
Modules & Packages
import math from math import sqrt from math import sqrt as square_root import math as m
def greet(name): return f"Hi {name}"
import helpers helpers.greet("Ada")
def main(): print("running as a script") if name == "main": main()
Tip:Tip: this guard lets a file be imported elsewhere without automatically running its script code.
File Handling
with open("data.txt", "r") as f: contents = f.read() # whole file as one string with open("data.txt", "r") as f: for line in f: # memory-efficient line by line print(line.strip())
with open("out.txt", "w") as f: # 'w' overwrites! f.write("hello\n") with open("out.txt", "a") as f: # 'a' appends f.write("more text\n")
Mode Meaning r read (default, error if missing) w write (creates/overwrites) a append (creates if missing) x create, error if exists rb / wb binary read/write
import csv, json with open("data.csv") as f: reader = csv.DictReader(f) for row in reader: print(row) with open("data.json") as f: obj = json.load(f) json.dumps(obj, indent=2) # dict -> JSON string Tip:Tip: with automatically closes the file for you, even if an error occurs.
OOP: Classes & Objects
class Dog: species = "Canis familiaris" # class attribute (shared) def init(self, name, age): self.name = name # instance attribute self.age = age def bark(self): return f"{self.name} says woof!"
rex = Dog("Rex", 3) rex.bark() # 'Rex says woof!' rex.name # 'Rex' Dog.species # shared by all instances
class Circle: def init(self, r): self.r = r @staticmethod def unit_circle(): # doesn't need self or cls return Circle(1) @classmethod def from_diameter(cls, d): # receives the class itself return cls(d / 2) Tip:Tip: use @property to make a method callable like an attribute:^ obj.area^ instead of^ obj.area()^.
OOP: Inheritance & Polymorphism
class Animal: def init(self, name): self.name = name def speak(self): return "..." class Dog(Animal): # Dog inherits from Animal def speak(self): # override return f"{self.name} says Woof!" class Puppy(Dog): def speak(self): return super().speak() + " (but tiny)" # call parent version
for pet in [Dog("Rex"), Animal("thing")]: print(pet.speak()) # each uses its own speak()
class Account: def init(self, balance): self._balance = balance # _ = "internal use" convention self.__pin = "1234" # __ triggers name-mangling @property def balance(self): return self._balance Gotcha:Gotcha: Python has no true "private" -- leading underscores are conventions, not enforced (double underscore just mangles the name to _ClassName__pin ).
class Flyer: def move(self): return "flies" class Swimmer: def move(self): return "swims" class Duck(Flyer, Swimmer): # MRO decides which move() wins pass Check method resolution order any time with ClassName.mro.