UNIT 2: Python Programming Fundamentals & Data Structures
2.1. Control Flow & Logic
Conditional Statements
-
if/elif/elsefor branching logic. -
Nested conditionals are allowed but should be minimized for readability.
-
Ternary Conditional Operator:
value_if_true if condition else value_if_falseresult = "Pass" if score >= 40 else "Fail"
Loops
-
forloop: 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.
-
-
whileloop: Repeats as long as condition isTrue. Risk of infinite loops. -
break: Exits the nearest enclosing loop. -
continue: Skips to the next iteration of the nearest enclosing loop. -
Loop
elseclause: Executes after loop completes normally (i.e., not viabreak).[!TIP] Common Pitfall:
elseon afor/whileruns only if the loop wasn't terminated bybreak.
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
Noneby default if noreturnstatement. -
Can return multiple values as a tuple:
return a, b, c
Variable Scope
-
Local: Inside function/class.
-
Global: At module top-level.
-
globalkeyword: Modify global var inside function. -
nonlocalkeyword: Refer to variable in enclosing (non-global) scope (nested functions).
Lambda Functions
-
Anonymous, single-expression functions.
-
Syntax:
lambda arguments: expressionfunc = 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)–Trueif any element truthy. -
all(iterable)–Trueif 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)| Addxto end | |extend(iter)| Append all from iterable | |insert(i, x)| Insertxat indexi| |remove(x)| Remove first occurrence ofx| |pop([i])| Remove & return item ati(default last) | |index(x)| Return first index ofx| |count(x)| Count occurrences ofx| |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 (
-1is last). -
Omitted
start/stopdefault to beginning/end. -
stepcan 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. Usecollections.dequefor efficient FIFO.
-
Tuples
-
Immutable, ordered sequence.
-
Packing/Unpacking:
a, b = (1, 2)ora, b = 1, 2. -
namedtuple(fromcollections): 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)– readsizechars/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
-
csvmodule:csv.reader(),csv.writer()for tabular data. -
jsonmodule: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 viamodule.name. -
from module import name– accessnamedirectly. -
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
.pyfile. 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 infor. -
Iterator: Object with
__next__()(and__iter__()returning self). Produces values on demand. -
iter(iterable)returns an iterator. -
next(iterator, default)returns next item ordefaultifStopIteration.
Generators
-
Generator Function: Uses
yieldinstead ofreturn. 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:
@decoratorabovedef.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 getint()(0). -
Counter:Counter('abracadabra')– counts hashable objects. -
deque:d = deque([1,2,3])– fastappendleft(),popleft().
[!TIP] Exam Focus: Be prepared to write code for:
- List/dict comprehensions with conditions.
- Functions using
*args/**kwargs.
- File reading/writing with
with.
- Handling specific exceptions (
ValueError,KeyError).
- Slicing with negative steps.
- Using
enumerate/zipin loops.
- Explaining scope and
global/nonlocal.