Skip to content
EX-406 · Python/Quick Revision Short Notes

Python (EX-406) - Unit 2 Short Notes

UNIT 2: Python Programming Fundamentals & Data Structures


2.1. Control Flow & Logic

Conditional Statements

  • if / elif / else for branching logic.

  • Nested conditionals are allowed but should be minimized for readability.

  • Ternary Conditional Operator: value_if_true if condition else value_if_false

    
    result = "Pass" if score >= 40 else "Fail"
    
    

Loops

  • for loop: Iterates over any iterable (sequence, dict, file, etc.).

    • range(start, stop, step) generates number sequences.

    • enumerate(iterable) yields (index, value) pairs.

    • zip(iter1, iter2, ...) aggregates elements from multiple iterables.

  • while loop: Repeats as long as condition is True. Risk of infinite loops.

  • break: Exits the nearest enclosing loop.

  • continue: Skips to the next iteration of the nearest enclosing loop.

  • Loop else clause: Executes after loop completes normally (i.e., not via break).

    [!TIP] Common Pitfall: else on a for/while runs only if the loop wasn't terminated by break.

Comprehensions

  • Concise syntax for creating lists, dicts, sets.

  • List Comprehension: [expression for item in iterable if condition]

    
    squares = [x**2 for x in range(10) if x % 2 == 0]
    
    
  • Dict Comprehension: {key_expr: value_expr for item in iterable}

  • Set Comprehension: {expression for item in iterable}

  • Generator Expression: (expression for item in iterable) – lazy evaluation, returns an iterator.


2.2. Functions & Modularity

Defining & Calling


def function_name(param1, param2="default"):

    """Docstring explaining function."""

    # function body

    return result  # Optional

Parameters & Arguments

  • Positional Arguments: Must match order.

  • Keyword Arguments: func(param=value) – order doesn't matter.

  • Default Values: Defined in def; evaluated once at definition.

  • Variable-Length Arguments:

    • *args – tuple of positional extra arguments.

    • **kwargs – dict of keyword extra arguments.

    
    def example(*args, **kwargs):
    
        print(args)   # tuple
    
        print(kwargs) # dict
    
    

Return Values

  • Returns None by default if no return statement.

  • Can return multiple values as a tuple: return a, b, c

Variable Scope

  • Local: Inside function/class.

  • Global: At module top-level.

  • global keyword: Modify global var inside function.

  • nonlocal keyword: Refer to variable in enclosing (non-global) scope (nested functions).

Lambda Functions

  • Anonymous, single-expression functions.

  • Syntax: lambda arguments: expression

    
    func = lambda x: x * 2
    
    sorted(list_of_tuples, key=lambda t: t[1])
    
    

    \boxed{\text{lambda } \text{args: expression}}

Built-in Functions (Key)

  • len(), sum(), min(), max(), sorted()

  • any(iterable) – True if any element truthy.

  • all(iterable) – True if all elements truthy.

  • enumerate(), zip() – as described in 2.1.


2.3. Core Data Structures (In-Depth)

Lists

  • Mutable, ordered sequence.

  • Common Methods:

    | Method | Action | |--------|--------| | append(x) | Add x to end | | extend(iter) | Append all from iterable | | insert(i, x) | Insert x at index i | | remove(x) | Remove first occurrence of x | | pop([i]) | Remove & return item at i (default last) | | index(x) | Return first index of x | | count(x) | Count occurrences of x | | sort(key=None, reverse=False) | In-place sort | | reverse() | In-place reverse |

  • Slicing: list[start:stop:step] – creates a new list.

    • Negative indices count from end (-1 is last).

    • Omitted start/stop default to beginning/end.

    • step can be negative for reverse.

    
    lst = [0,1,2,3,4,5]
    
    lst[1:4]   # [1,2,3]
    
    lst[::-1]  # [5,4,3,2,1,0]
    
    

    \boxed{\text{slice: } [\text{start} : \text{stop} : \text{step}]}

  • As Stack/Queue:

    • Stack (LIFO): append() + pop().

    • Queue (FIFO): pop(0) is O(n) – inefficient. Use collections.deque for efficient FIFO.

Tuples

  • Immutable, ordered sequence.

  • Packing/Unpacking: a, b = (1, 2) or a, b = 1, 2.

  • namedtuple (from collections): Creates tuple subclasses with named fields.

Dictionaries

  • Key-value mappings. Keys must be immutable (str, num, tuple).

  • Common Methods:

    | Method | Returns | |--------|---------| | keys() | view of keys | | values() | view of values | | items() | view of (key, value) tuples | | get(key, default=None) | value or default (no KeyError) | | pop(key) | remove & return value | | update(other_dict) | merge dicts |

  • Dictionary Comprehension: {k: v for k, v in iterable}

  • collections.defaultdict(default_factory): Returns default for missing keys.

  • collections.OrderedDict: Preserves insertion order (Python 3.7+ dicts do this by default).

Sets

  • Unordered collection of unique, immutable elements.

  • Operations:

    | Operation | Symbol | Method | |-----------|--------|--------| | Union | \| | union() | | Intersection | & | intersection() | | Difference | - | difference() | | Symmetric Diff | ^ | symmetric_difference() |

  • Common Methods: add(), remove() (raises KeyError), discard() (no error), pop() (remove arbitrary), clear().

  • Set Comprehension: {expression for item in iterable if condition}


2.4. File Input/Output (I/O)

File Operations

  • open(file, mode='r', encoding=None) – returns a file object.

  • Modes: 'r' (read), 'w' (write, truncate), 'a' (append), 'x' (exclusive create), 'b' (binary), 't' (text, default). Combine: 'rb', 'w+' etc.

  • Always close files: file.close().

Context Manager (with statement) – BEST PRACTICE


with open('file.txt', 'r') as f:

    data = f.read()

# File automatically closed here, even on error.

Reading

  • f.read(size=-1) – read size chars/bytes (all if -1).

  • f.readline() – read one line (including newline).

  • f.readlines() – read all lines into a list.

  • Iterating: for line in f: – memory efficient, line by line.

Writing

  • f.write(str) – write string.

  • f.writelines(list_of_strings) – write each string (no newlines added automatically).

CSV/JSON

  • csv module: csv.reader(), csv.writer() for tabular data.

  • json module: json.load(f) (read), json.dump(obj, f) (write). Converts between Python objects and JSON strings.


2.5. Error Handling & Exceptions

Exceptions vs. Syntax Errors

  • Syntax Errors: Code not valid Python (caught at compile time).

  • Exceptions: Runtime errors (e.g., ZeroDivisionError, TypeError).

try / except / else / finally


try:

    # risky code

    result = 10 / 0

except ZeroDivisionError as e:

    # handle specific exception

    print("Cannot divide by zero")

except (TypeError, ValueError) as e:

    # handle multiple exceptions

    print(f"Error: {e}")

except Exception as e:

    # catch-all (use sparingly)

    print(f"Unexpected: {e}")

else:

    # runs if NO exception raised in try block

    print("Operation successful")

finally:

    # runs ALWAYS (cleanup code)

    file.close()

\boxed{\text{try: } \text{except: } \text{else: } \text{finally:}}

Common Built-in Exceptions

  • ValueError, TypeError, IndexError (list/tuple), KeyError (dict), FileNotFoundError, IOError, AttributeError, ImportError.

Raising Exceptions


if x < 0:

    raise ValueError("x must be non-negative")

# Or re-raise:

except SomeError:

    raise  # re-raises current exception


2.6. Modules & Packages

Importing

  • import module – access via module.name.

  • from module import name – access name directly.

  • import module as alias – use shorter name.

  • from module import * – discouraged (pollutes namespace).

Standard Library (Key Modules)

  • math: sqrt(), pi, ceil(), floor().

  • random: randint(), choice(), shuffle().

  • datetime: datetime.now(), date, time.

  • statistics: mean(), median(), stdev().

Creating Modules & Packages

  • Module: Any .py file. Its name is the filename.

  • Package: Directory containing __init__.py (can be empty). Allows dot notation: from package.sub import module.

  • __name__ == "__main__" idiom:

    
    if __name__ == "__main__":
    
        # code here runs only if script executed directly (not imported)
    
        main()
    
    

2.7. Advanced Topics (If Covered)

Iterators & Iterables

  • Iterable: Object with __iter__() or __getitem__() (e.g., list, str, dict). Can be used in for.

  • Iterator: Object with __next__() (and __iter__() returning self). Produces values on demand.

  • iter(iterable) returns an iterator.

  • next(iterator, default) returns next item or default if StopIteration.

Generators

  • Generator Function: Uses yield instead of return. Produces iterator lazily.

    
    def count_up_to(n):
    
        i = 0
    
        while i < n:
    
            yield i
    
            i += 1
    
    
  • Generator Expression: (x**2 for x in range(10)) – like list comp but lazy.

Decorators (Basic)

  • Function that takes a function and returns a modified function.

  • Syntax: @decorator above def.

    
    def my_decorator(func):
    
        def wrapper():
    
            print("Before")
    
            func()
    
            print("After")
    
        return wrapper
    
    @my_decorator
    
    def say_hello():
    
        print("Hello")
    
    

collections Module

  • namedtuple: Point = namedtuple('Point', 'x y')

  • defaultdict: dd = defaultdict(int) – missing keys get int() (0).

  • Counter: Counter('abracadabra') – counts hashable objects.

  • deque: d = deque([1,2,3]) – fast appendleft(), popleft().

[!TIP] Exam Focus: Be prepared to write code for:

  1. List/dict comprehensions with conditions.
  1. Functions using *args/**kwargs.
  1. File reading/writing with with.
  1. Handling specific exceptions (ValueError, KeyError).
  1. Slicing with negative steps.
  1. Using enumerate/zip in loops.
  1. Explaining scope and global/nonlocal.
Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in