Docsity

Python language full course, Summaries of Project Management

Toggle sidebar
bg1
M Y N O T E B O O K
PYTHON
FULLCOURSE
NOTES
Beginner→Advanced·syntax,examples,gotchas&cheatsheets,all
inoneplace.
Chapters1–23·Compiledstudynotes
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download Python language full course and more Summaries Project Management in PDF only on Docsity!

M Y N O T E B O O K

PYTHON

FULL COURSE

NOTES

Beginner → Advanced · syntax, examples, gotchas & cheat sheets, all

in one place.

Chapters 1–23 · Compiled study notes

C O N T E N T S

**Table of Contents

Chapter # Chapter**

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

✦ Declaring Variables

No need to declare a type -- Python figures it out.

name = "Ada" age = 28 height = 1. is_coder = True

✦ Core Data Types

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"

✦ Checking & Converting Types

type(age) # str(age) # "28" int("28") # 28 float("3.14") # 3. bool(0), bool(1) # False, True

✦ Naming Rules

➞ Letters, numbers, underscores only; can't start with a number.

➞ Case-sensitive: age ≠ Age.

➞ Convention: snake_case for variables/functions, PascalCase for classes, UPPER_CASE for

constants.

✦ Multiple Assignment

x, y, z = 1, 2, 3 a = b = c = 0 Tip:Tip: everything in Python is an object -- even functions and classes.

Operators

✦ Arithmetic

Op Meaning Example

      • / add, subtract, multiply, divide 7 / 2 → 3. // floor division 7 // 2 → 3 % modulo (remainder) 7 % 2 → 1 ** exponent 2 ** 3 → 8

✦ Comparison

== != > < >= <= — all return a boolbool.

✦ Logical

and , or , not -- combine boolean expressions.

age = 20 is_member = True age >= 18 and is_member # True

✦ Assignment Shortcuts

✦ Identity vs Equality

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 ).

✦ Membership

"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()

print("a", "b", sep="-", end="!\n") # a-b!

✦ input()

input() always returns a stringstring -- convert it if you need a number.

name = input("What's your name? ") age = int(input("Age? "))

✦ Formatting Numbers

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

✦ if / elif / else

age = 20 if age < 13: print("child") elif age < 20: print("teen") else: print("adult")

✦ Ternary (one-line if)

status = "adult" if age >= 18 else "minor"

✦ Truthy & Falsy

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

items = [] if not items: print("list is empty")

✦ match / case (Python 3.10+)

match command: case "start": print("starting") case "stop": print("stopping") case _: print("unknown") Gotcha:Gotcha: don't confuse = (assignment) with == (comparison) inside conditions.

Lists

✦ Basics

nums = [3, 1, 4, 1, 5] nums[0] # 3 nums[-1] # 5 nums[1:3] # [1, 4] len(nums) # 5

✦ Mutating Methods

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

✦ Non-mutating helpers

sorted(nums) # new sorted list sum(nums), min(nums), max(nums) list(reversed(nums))

✦ Copying (watch out!)

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.

✦ Nested Lists

grid = [[1, 2], [3, 4]] grid[1][0] # 3

Tuples & Sets

✦ Tuples

➞ Ordered, like lists, but immutableimmutable -- can't change after creation.

➞ Faster and safer for fixed collections (coordinates, RGB values...).

point = (3, 4) x, y = point # unpacking single = (5,) # trailing comma required for 1-item tuple!

✦ Sets

➞ Unordered collection of uniqueunique items. Great for de-duping and membership tests.

s = {1, 2, 2, 3} # {1, 2, 3} s.add(4) s.remove(1) 3 in s # True (fast lookup)

✦ Set Operations

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

✦ Defining & Calling

def greet(name): return f"Hello, {name}!" greet("Ada") # 'Hello, Ada!'

✦ Default & Keyword Arguments

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)

✦ Return Values

def divmod_custom(a, b): return a // b, a % b # returns a tuple q, r = divmod_custom(7, 2)

✦ Docstrings

def add(a, b): """Return the sum of a and b.""" return a + b

✦ Type Hints (optional, but recommended)

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

✦ *args -- variable positional args

def total(*nums): return sum(nums) total(1, 2, 3) # 6 -- nums is a tuple (1,2,3)

✦ **kwargs -- variable keyword args

def profile(**info): for k, v in info.items(): print(k, v) profile(name="Ada", age=28) # info is a dict

✦ Unpacking when calling

nums = [1, 2, 3] total(nums) # unpack list into positional args info = {"name": "Ada"} profile(*info) # unpack dict into keyword args

✦ Scope: Local vs Global

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.

✦ Closures

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

✦ Importing

import math from math import sqrt from math import sqrt as square_root import math as m

✦ Your Own Module

file: helpers.py

def greet(name): return f"Hi {name}"

file: main.py

import helpers helpers.greet("Ada")

✦ if name == "main"

def main(): print("running as a script") if name == "main": main()

✦ Packages

➞ A folder with an init.py (can be empty) becomes an importable package.

➞ Install third-party packages with pip install package_name.

Tip:Tip: this guard lets a file be imported elsewhere without automatically running its script code.

File Handling

✦ Reading

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())

✦ Writing

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")

✦ File Modes

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

✦ Working with CSV / JSON

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

✦ Defining a Class

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!"

✦ Creating & Using Objects

rex = Dog("Rex", 3) rex.bark() # 'Rex says woof!' rex.name # 'Rex' Dog.species # shared by all instances

✦ self explained

➞ self refers to the specific instance calling the method -- Python passes it automatically.

➞ Every instance method's first parameter must be self (by convention, not a keyword).

✦ init -- the constructor

Runs automatically when a new object is created; sets up its starting attributes.

✦ Class Methods & Static Methods

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

✦ Inheritance

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

✦ Polymorphism

Different classes respond to the same method call in their own way:

for pet in [Dog("Rex"), Animal("thing")]: print(pet.speak()) # each uses its own speak()

✦ Encapsulation

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 ).

✦ Multiple Inheritance

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.