Skip to content
Unit 3 Syllabus Note· Programming in Python

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

Python
1if condition1:
2 # statements
3elif condition2:
4 # statements
5else:
6 # default statements

How 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:

  1. L - Local: Inside the currently executing function.
  2. E - Enclosing: Inside enclosing/nested functions (from nearest to furthest).
  3. G - Global: At top-level of module or declared with global.
  4. 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:

  1. Base Case: Halting condition that stops recursion.
  2. Recursive Step: Progress toward base case.

Python protects against infinite stack overflows via sys.getrecursionlimit() (default 1,000):

Python
1import sys
2print("Current limit:", sys.getrecursionlimit()) # 1000
3sys.setrecursionlimit(2000) # Increases limit if strictly necessary

map(), filter(), and reduce() Built-in Functional Utilities

FunctionPurposeSyntaxExample
`map()`Applies a function to all items in an iterablemap(func, iterable)list(map(lambda x: x*2, [1,2,3])) -> [2,4,6]
`filter()`Filters elements where condition function returns Truefilter(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.

Python
1# BAD: Default list persists across calls
2def append_bad(val, lst=[]):
3 lst.append(val)
4 return lst
5
6# GOOD: Using None as sentinel
7def append_good(val, lst=None):
8 if lst is None:
9 lst = []
10 lst.append(val)
11 return lst

In-Depth Analysis & Implementation

Write a Complete Recursive Program in Python for the Towers of Hanoi Problem with Step-by-Step Move Logging

System Architecture / Concept DiagramHorizontal Scroll Enabled
"""
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.

Python
1import time
2from functools import wraps
3
4# Execution Timing Decorator
5def execution_timer(func):
6 @wraps(func) # Preserves original function name and docstring
7 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 result
13 return wrapper
14
15# Applying Decorator using @ syntactic sugar
16@execution_timer
17def calculate_factorial(n):
18 """Calculates factorial recursively."""
19 fact = 1
20 for i in range(1, n + 1):
21 fact *= i
22 return fact
23
24# Invocation
25val = 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

Python
1# QuickSort and Binary Search Implementation
2
3def quicksort(arr):
4 """Divide-and-conquer QuickSort: Average O(n log n), Worst O(n^2)"""
5 if len(arr) <= 1:
6 return arr
7 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 = 0
16 high = len(arr) - 1
17 while low <= high:
18 mid = (low + high) // 2
19 if arr[mid] == target:
20 return mid
21 elif arr[mid] < target:
22 low = mid + 1
23 else:
24 high = mid - 1
25 return -1
26
27data = [45, 12, 85, 32, 89, 39, 69, 44, 42, 1, 10]
28sorted_data = quicksort(data)
29print("Sorted Array:", sorted_data)
30
31target = 42
32idx = 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.

Your reading progress
0%

100% left on this page — finishing it closes the gap for Decision Making, Branching, Iteration & Functions.

Weak topic hint

Decision Making, Branching, Iteration & Functions still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.