Python Programming Fundamentals – Comprehensive Notes

Variables, Assignment & Mutability

  • A variable comes into existence the moment a value is assigned to an identifier.
  • Re-assignment changes the reference, not the underlying object.
  • Immutable objects (e.g. intint, floatfloat, strstr, tupletuple) cannot be altered in-place; a new object is created when their value appears to change.
  • Mutable objects (e.g. listlist, dictdict, setset, most user-defined objects) can be changed without creating a new object.
  • Automatic garbage collection frees objects with no remaining references.

Identifiers & Keywords

  • Identifiers must start with A–Z, a–z or _ and may contain digits thereafter.
  • They are case–sensitive (e.g. totaltotalTotalTotal).
  • Do not use reserved keywords as identifiers (and, or, not, if, …).
  • Follow PEP-8 naming conventions: lowercasewithunderscores for variables / functions; UpperCamelCase for classes.

Boolean Logic

  • Core operators: not, and, or (short-circuit evaluation).
    • True and TrueTrue\text{True and True} \Rightarrow \text{True}
    • True and FalseFalse\text{True and False} \Rightarrow \text{False}
    • not False and FalseFalse\text{not False and False} \Rightarrow \text{False} (because ¬False=True\lnot\text{False}=\text{True} then TrueFalse=False\text{True}\land \text{False}=\text{False})
  • Truthiness: every object has an implicit Boolean value (0, 0.0, '', [], {}, None evaluate to False\text{False}; everything else True\text{True}).

Lists

  • Literal syntax: lst = [12, 68, 34, 5, 93, 63, 29, 29, 0].
  • Indexing & slicing (zero-based):
    • lst[0]=12\text{lst}[0] = 12
    • lst[2:4]=[34,5]\text{lst}[2:4] = [34,5] (stop index excluded)
    • lst[:1]\text{lst}[:-1] returns all except last element.
    • General form a[i:j:k]a[i:j:k] where kk is the step.
  • Common methods: append, extend, insert, pop, remove, index, count, reverse, sort.
  • Built-ins usable on lists: len(lst), sum(lst), max(lst), min(lst), sorted(lst) (returns new list).

Tuples vs Lists

  • Tuple literal: (1, 23).
  • Tuples are immutable; lists are mutable.
  • Use tuples for fixed collections (e.g. points (x, y)), lists for variable collections.

Dictionaries

  • Literal example: d = {'a':2000, 'b':300, 'c':3000, 'd':1400, 'e':2500, 'f':3000}.
  • Access: d['a'] -> 2000.
  • Membership: 'a' in d # True checks keys.
  • Important methods: keys(), values(), items(), get(key, default), pop, update.

String Operations & Slicing

  • Strings behave like immutable sequences of characters.
    • s[0] → first character; s[-1] → last.
    • s[::2] → every second character.
  • Concatenation with +, repetition with *.
  • Useful methods: lower, upper, strip, find, replace, split, join.

Functions

  • Declared with the def keyword.
 def add(a, b):
     """Return the sum of a and b."""
     return a + b
  • Components of a function definition
    • def keyword + function name.
    • Parameters (positional, default, *args, **kwargs).
    • Optional doc-string enclosed in triple quotes.
    • Body (indented block).
    • Optional return statement – if absent, the function returns None\text{None}.
  • Example of default & keyword arguments:
 def add(a, b=30):
     return a + b

 add(10)          # 40 (uses default b)
 add(b=5, a=10)   # 15 (keyword order free)
  • A function without return only produces side-effects (e.g. printing) and implicitly returns None\text{None}.

First-Class & Higher-Order Functions

  • Functions are objects: can be assigned to variables, stored in containers, passed as arguments, returned by other functions.
  • Example: assigning a function
 f = add
 print(f(2, 3))   # 5

Fibonacci Examples

 def fib_print(n):
     """Print Fibonacci series up to n (side-effect only)."""
     a, b = 0, 1
     while b <= n:
         print(b, end=' ')
         a, b = b, a + b

 def fib_list(n):
     """Return a list containing the Fibonacci series up to n."""
     result = []
     a, b = 0, 1
     while b <= n:
         result.append(b)
         a, b = b, a + b
     return result

Calling fib_list(100)[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89].

Counting Vowels Example

 def count_vowel(w):
     vowels = 'aeiouAEIOU'
     total = 0
     for ch in w:
         if ch in vowels:
             total += 1
     return total

Argument Passing Semantics

  • Python uses pass-by-object-reference (a.k.a. “shared” semantics).
  • Mutable arguments changed in-place inside a function affect the caller’s object.
 def mutate(lst):
     lst.append(99)

 nums = [0, 1, 2]
 mutate(nums)
 print(nums)   # [0, 1, 2, 99]
  • Re-binding the parameter inside the function creates a new local reference and leaves the caller unchanged.

Variable Scope

  • Local scope – identifiers assigned within a function.
  • Global scope – module-level identifiers.
  • Use global name inside a function to bind to the global variable.
 total = 0
 def accumulate(x):
     global total
     total += x
  • Rule of thumb: read-only access to global variables is allowed, assignment requires global (or nonlocal for nested defs).

Control Flow & Looping

  • if, elif, else for selection.
  • for item in iterable: loops over any sequence.
  • while condition: loops until the condition becomes false.
  • break, continue for loop control.

Common Built-In Functions & Methods (selected)

  • type(obj), id(obj), isinstance(obj, cls) – introspection.
  • input(prompt) – returns user input as str.
  • int(x, base=10) – converts string to integer with optional base (e.g. int('101', 2) == 5).
  • enumerate(seq) – yields (index, value) pairs.
  • zip(a, b, …) – parallel iteration.
  • map(func, iterable), filter(func, iterable) – functional helpers.

Error Messages & Debugging Hints

  • SyntaxError often thrown by
    • uneven parentheses, unmatched quotes,
    • invalid identifiers (e.g. starting with digit or containing spaces),
    • using a keyword as a variable.
  • IndexError: list index out of range – slice safely or validate length.
  • TypeError appears when applying an operation to incompatible types (e.g. concatenating str and int).

Practical Coding Guidelines (Peppered Through Transcript)

  • Always initialise variables before use.
  • Prefer snake_case for variables and functions.
  • Keep functions small – one well-defined task.
  • Document with doc-strings: first line short summary, optional detailed description following a blank line.
  • Use meaningful names (count_vowels better than cv).

Real-World Relevance & Best-Practices

  • Mutability awareness prevents subtle bugs (sharing same list across function calls).
  • Keyword arguments improve readability and reduce ordering errors.
  • Doc-strings + built-in help() enable self-documenting code.
  • Mastering slicing produces concise data-processing pipelines.
  • Understanding scope is crucial for maintaining large code-bases.

Mini-Reference: Frequently Used Syntax

  • List literal: [e_1, e_2, …]
  • Tuple literal: (e_1, e_2, …)
  • Dict literal: {key_1: val_1, …}
  • Slice: seq[start:stop:step] ⇢ \text{start}\le i<\text{stop}, increment stepstep.
  • Function: def name(params): … return value.
  • Lambda: lambda x, y=0: x + y (anonymous inline function).