Skip to main content

46. Mid-Way Mental Map

1.2 CORE BASICS

Everything is an object. Know your containers.

The "Big Four" Collections

StructureSyntaxMutable?Ordered?Best Used For...
Listx = [1, 2, "a"]YesYesGeneral sequences, updating items.
Tuplex = (1, 2, "a")NoYesFixed records, dictionary keys.
Setx = {1, 2, "a"}YesNoRemoving duplicates, math logic (union/intersection).
Dictx = {"k": "v"}YesYesLookups, mapping keys to values, structured data[cite: 379, 384].

Essential Operations

  • Strings: Use f-strings for formatting: f"Hello {name}". Use raw strings for paths: r"C:\path\to\file".
  • Slicing: sequence[start:stop:step]. Example: my_list[::-1] reverses a list.
  • Type Casting: int("5"), str(42), list((1, 2, 3)).
  • Booleans & Logic: Falsy values include 0, "", [], {}, None, and False. Everything else evaluates to True. Combine with and, or, not.

1.3: CONTROL FLOW

Directing the traffic of your program.

Conditionals

Check conditions from most specific to least specific. Python checks conditions top to bottom.

if score >= 90:
print("A")
elif score >= 80: # Only checked if the 'if' is False
print("B")
else: # Catch-all
print("Study harder!")

Loops

  • for loops: Used when the number of iterations is known (iterating over lists, strings, range())[cite: 447, 448].
  • while loops: Used when iterations depend on a condition remaining True. Watch out for infinite loops!
  • Loop Control:
    • break: Exits the innermost loop entirely[cite: 468, 470].
    • continue: Skips the rest of the current iteration and moves to the next[cite: 468, 471].
    • pass: Does absolutely nothing (acts as a structural placeholder)[cite: 469, 473].

Comprehensions

The Pythonic, readable way to create collections from existing iterables.

# [expression for item in iterable if condition]
evens = [x for x in range(10) if x % 2 == 0]

1.4 FUNCTIONS, SCOPE & ENVIRONMENT

Building reusable, modular, and isolated code.

Anatomy of a Function

def process_data(required_arg, default_arg="Hello", *args, **kwargs):
"""Docstring: Explains what the function does."""
# *args collects extra positional arguments into a TUPLE.
# **kwargs collects extra keyword arguments into a DICT.
return result

Scope Resolution (LEGB Rule)

Python checks for variables in this order:

  1. Local: Inside the current function.
  2. Enclosing: Inside any enclosing (nested) functions.
  3. Global: Defined at the top level of the script. (Use the global keyword to modify these inside a function ).
  4. Built-in: Python's reserved names (like len or print).

Modules & Environments

  • Importing: import my_module or from my_module import my_func[cite: 535, 536]. Keep your custom modules focused and small.
  • Virtual Environments (venv): Project-specific sandboxes for your dependencies so you don't break your global Python installation.
    • Create: python3 -m venv venv
    • Activate (Linux/Mac): source venv/bin/activate
  • Package Management (pip):
    • Save state: pip freeze > requirements.txt
    • Install state: pip install -r requirements.txt