Programming in Python
Comprehensive exam revision notes for BCA-202N Unit 3 (Decision Making, Branching, Iteration & Functions). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
Programming in Python
Decision Making, Branching, Iteration & Functions
Core Definitions & Key Concepts
What is the syntax of the if-elif-else ladder in Python
1if condition1:2 # statements3elif condition2:4 # statements5else:6 # default statementsHow does the else block behave in a for or while loop in Python
The else block executes only if the loop terminates normally (without encountering a break statement). If the loop exits via break, the else block is skipped.
break and continue
break: Immediately terminates the entire loop and transfers control to the statement after the loop.continue: Aborts the remainder of the current iteration and jumps to the next iteration of the loop.
What is the difference between positional arguments and keyword arguments
- Positional arguments must be passed in the exact order declared in the function signature.
- Keyword arguments are passed by explicit parameter name (
func(age=20, name='Amit')), allowing arbitrary order.
*args and **kwargs in Python function definitions
*args: Collects an arbitrary number of extra positional arguments into a tuple.**kwargs: Collects an arbitrary number of extra keyword arguments into a dictionary.
What are lambda functions in Python
Lambda functions are anonymous, single-line functions created with the lambda keyword:
add = lambda a, b: a + b
They can take any number of arguments but contain only a single expression whose evaluated value is returned.
What is the purpose of the global keyword
The global keyword tells Python that a variable assignment inside a local function scope refers to a global variable defined outside, preventing the creation of a local shadow variable.
What does the nonlocal keyword do
nonlocal binds an identifier to a variable in the nearest enclosing (outer) non-global function scope, essential in nested functions and closures.
Conceptual & Architectural Analysis
The LEGB Rule for Variable Scope Resolution in Python
The LEGB Scope Hierarchy
When a variable is referenced in Python, the interpreter searches four scopes sequentially:
- L - Local: Inside the currently executing function.
- E - Enclosing: Inside enclosing/nested functions (from nearest to furthest).
- G - Global: At top-level of module or declared with
global. - B - Built-in: Python's pre-loaded standard namespace (
print,len,range,ValueError).
If the identifier is not found in any of these four scopes, Python raises a NameError.
Recursion in Python and How Recursion Limit is Managed
Recursion occurs when a function calls itself to solve smaller sub-problems. Every recursive function requires:
- Base Case: Halting condition that stops recursion.
- Recursive Step: Progress toward base case.
Python protects against infinite stack overflows via sys.getrecursionlimit() (default 1,000):
1import sys2print("Current limit:", sys.getrecursionlimit()) # 10003sys.setrecursionlimit(2000) # Increases limit if strictly necessarymap(), filter(), and reduce() Built-in Functional Utilities
| Function | Purpose | Syntax | Example |
|---|---|---|---|
| `map()` | Applies a function to all items in an iterable | map(func, iterable) | list(map(lambda x: x*2, [1,2,3])) -> [2,4,6] |
| `filter()` | Filters elements where condition function returns True | filter(func, iterable) | list(filter(lambda x: x%2==0, [1,2,3,4])) -> [2,4] |
| `reduce()` | Cumulatively reduces iterable to single scalar value (from functools) | reduce(func, iterable) | reduce(lambda a,b: a*b, [1,2,3,4]) -> 24 |
Default Arguments and the 'Mutable Default Argument' Trap
Default argument expressions are evaluated once at function definition time, not each time the function is called.
1# BAD: Default list persists across calls2def append_bad(val, lst=[]):3 lst.append(val)4 return lst5
6# GOOD: Using None as sentinel7def append_good(val, lst=None):8 if lst is None:9 lst = []10 lst.append(val)11 return lstIn-Depth Analysis & Implementation
Write a Complete Recursive Program in Python for the Towers of Hanoi Problem with Step-by-Step Move Logging
"""
MJPRU Examination Model Program: Unit 3
Towers of Hanoi - Recursive Mathematical Solution
"""
def towers_of_hanoi(n, source_rod, destination_rod, auxiliary_rod):
"""
Solves Towers of Hanoi puzzle for n disks.
Total moves required = 2^n - 1
Time Complexity: O(2^n)
"""
if n == 1:
print(f"Move Disk 1 directly from Rod {source_rod} -> Rod {destination_rod}")
return 1
moves = 0
# Step 1: Move top n-1 disks from Source to Aux using Dest as helper
moves += towers_of_hanoi(n - 1, source_rod, auxiliary_rod, destination_rod)
# Step 2: Move the nth (largest) disk directly to Dest
print(f"Move Disk {n} from Rod {source_rod} -> Rod {destination_rod}")
moves += 1
# Step 3: Move the n-1 disks from Aux to Dest using Source as helper
moves += towers_of_hanoi(n - 1, auxiliary_rod, destination_rod, source_rod)
return moves
# Execution
disks = 3
print(f"Solving Towers of Hanoi for {disks} disks (Expected moves: {2**disks - 1}):\n")
total = towers_of_hanoi(disks, 'A', 'C', 'B')
print(f"\nPuzzle solved successfully in {total} total moves!")Python Decorators in Depth (Function Wrappers, @ syntax, and Decorators with Arguments) with Full Code
Comprehensive Guide to Python Decorators
A decorator is a design pattern that dynamically alters or extends the behavior of a function or method without permanently modifying its source code.
1import time2from functools import wraps3
4# Execution Timing Decorator5def execution_timer(func):6 @wraps(func) # Preserves original function name and docstring7 def wrapper(*args, **kwargs):8 start_time = time.perf_counter()9 result = func(*args, **kwargs)10 end_time = time.perf_counter()11 print(f"[PERF] Function '{func.__name__}' took {(end_time - start_time)*1000:.3f} ms")12 return result13 return wrapper14
15# Applying Decorator using @ syntactic sugar16@execution_timer17def calculate_factorial(n):18 """Calculates factorial recursively."""19 fact = 120 for i in range(1, n + 1):21 fact *= i22 return fact23
24# Invocation25val = calculate_factorial(5000)26print(f"Result length: {len(str(val))} digits")27print(f"Function Name preserved: {calculate_factorial.__name__}")Write a Program to Implement Binary Search and QuickSort Algorithms in Python with Big-O Complexity Analysis
1# QuickSort and Binary Search Implementation2
3def quicksort(arr):4 """Divide-and-conquer QuickSort: Average O(n log n), Worst O(n^2)"""5 if len(arr) <= 1:6 return arr7 pivot = arr[len(arr) // 2]8 left = [x for x in arr if x < pivot]9 middle = [x for x in arr if x == pivot]10 right = [x for x in arr if x > pivot]11 return quicksort(left) + middle + quicksort(right)12
13def binary_search(arr, target):14 """Binary search on sorted array: O(log n)"""15 low = 016 high = len(arr) - 117 while low <= high:18 mid = (low + high) // 219 if arr[mid] == target:20 return mid21 elif arr[mid] < target:22 low = mid + 123 else:24 high = mid - 125 return -126
27data = [45, 12, 85, 32, 89, 39, 69, 44, 42, 1, 10]28sorted_data = quicksort(data)29print("Sorted Array:", sorted_data)30
31target = 4232idx = binary_search(sorted_data, target)33print(f"Target {target} found at index: {idx}")Important Exam Points & Quick Revision
Master the Towers of Hanoi recursive derivation, LEGB variable scoping rules, and decorators with @wraps.
100% left on this page — finishing it closes the gap for Decision Making, Branching, Iteration & Functions.
Decision Making, Branching, Iteration & Functions still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.