14 Min Read • Study Chapter

Unit 3: Control Structures, Loops & Modular Functions in Python

Execution flow mechanics, nested loop algorithms, variable parameter unpacking (*args, **kwargs), scope rules, and university exam problem breakdowns

Control flow is the nervous system of any programming language. In Python (ADES204 Unit 3), mastering control flow means understanding how the interpreter traverses statements sequentially, branches dynamically based on Boolean truth values, repeats instructions through bounded and unbounded iterations, and encapsulates reusable logic inside modular functions. This unit constitutes 14–16 marks in autonomous end-term examinations, heavily emphasizing loop tracing, dry-running nested patterns, recursion, and argument-passing semantics.

1. Conditional Branching: if, elif, and else Statements

Python utilizes indentation rather than curly braces to define code blocks. The conditional statement evaluates an expression against Python's truth-value testing protocol (where 0, None, empty containers [], "", {} evaluate to False, and everything else evaluates to True).

Python 3 Chained Conditional Logic & Ternary Operator
# Grading system using chained conditionals
marks = 87.5

if marks >= 90:
    grade = "O (Outstanding)"
elif marks >= 80:
    grade = "A+ (Excellent)"
elif marks >= 70:
    grade = "A (Very Good)"
elif marks >= 40:
    grade = "P (Pass)"
else:
    grade = "F (Fail)"

# Python Conditional Expression (Ternary Operator)
status = "Eligible" if marks >= 60 else "Not Eligible"
print(f"Grade: {grade} | Placement Status: {status}")

2. Iterative Loops: while and for Structures

Python provides two fundamental looping constructs:

  • while Loop: Executes continuously as long as a Boolean condition remains True. Crucial for open-ended or event-driven tasks where the exact iteration count is unknown beforehand.
  • for Loop: Operates as an iterator-based loop that consumes elements from any iterable object (lists, strings, tuples, dictionaries, generators, or range()).
  • The else Clause in Loops: A unique Python feature! Both for and while loops can have an optional else block, which executes only if the loop completes normally without encountering a break statement.
Python 3 Prime Number Detection via for-else and break
def check_prime(n):
    if n <= 1:
        return False
    # Optimized trial division up to sqrt(n)
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            print(f"{n} is divisible by {i} -> Composite")
            break
    else:
        # Runs only if no divisor triggered break
        print(f"{n} has no factors -> Prime")

check_prime(29)
check_prime(49)

3. Loop Control Statements: break, continue, and pass

Three statements alter loop execution flow:

  1. break: Immediately terminates the innermost active loop and jumps to the next statement outside the loop.
  2. continue: Skips the remaining lines in the current iteration and jumps directly to the evaluation of the next cycle.
  3. pass: A syntactic null statement used as a placeholder where valid Python syntax requires a statement body (e.g., empty functions, stub classes).

4. Modular Functions & Advanced Parameter Passing

Functions in Python are defined with the def keyword and are first-class citizens: they can be assigned to variables, passed as arguments, and returned from other functions.

To write robust functions, you must understand Python's versatile parameter mechanisms:

⚙️ Parameter Types Breakdown

  • Positional Arguments: Matched strictly left-to-right based on order of declaration.
  • Keyword / Default Arguments: Specified with default values (e.g., def calc(x, y=10)). Default parameters must follow non-default parameters.
  • Variable Positional Arguments (*args): Bundles surplus positional arguments into a single immutable tuple.
  • Variable Keyword Arguments (**kwargs): Captures arbitrary named arguments into a mutable dictionary.
Python 3 Comprehensive *args and **kwargs Demonstration
def ai_model_summary(model_name, *metrics, **hyperparameters):
    print(f"=== Model Architecture: {model_name} ===")
    print(f"Logged Test Scores (Tuple via *args): {metrics}")
    print("Tuned Hyperparameters (Dict via **kwargs):")
    for key, val in hyperparameters.items():
        print(f"  - {key}: {val}")

# Calling with variable arguments:
ai_model_summary(
    "ResNet-50",
    0.942, 0.938, 0.951,
    learning_rate=0.001,
    batch_size=64,
    optimizer="AdamW"
)

5. Lambda (Anonymous) Functions & Functional Helpers

Anonymous one-liner functions are declared using the lambda keyword with the syntax: lambda arguments: expression. They are predominantly paired with higher-order functions like map(), filter(), and sorted().

Python 3 Lambda Functions with map, filter, and sorting
numbers = [1, 2, 3, 4, 5, 6, 7, 8]

# Filter even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))

# Square each number
squares = list(map(lambda x: x**2, numbers))

# Sort tuples by custom key (SGPA descending)
students = [("Rohan", 8.4), ("Priya", 9.7), ("Kiran", 9.1)]
students.sort(key=lambda item: item[1], reverse=True)

print("Evens:", evens)
print("Squares:", squares)
print("Ranked Students:", students)

6. Variable Scope: The LEGB Rule

When a variable is referenced inside a function, Python resolves its identifier using the LEGB priority hierarchy:

  1. Local (L): Names assigned within a function body or parameter list.
  2. Enclosing (E): Names in the local scope of any enclosing outer functions (closures).
  3. Global (G): Names assigned at the top-level of the script/module or explicitly flagged via global x.
  4. Built-in (B): Names pre-assigned into Python's built-in module (e.g., print, range, len).

7. Typical Autonomous ETE Exam Questions & Solutions

Q1: What is the output of the following nested loop snippet? Trace execution. (5 Marks)

Exam Problem:

for i in range(1, 4):
    for j in range(i):
        print(f"{i}*{j}", end=" ")
    print()

Answer Trace: For i=1: j takes 0 → prints 1*0. For i=2: j takes 0, 1 → prints 2*0 2*1. For i=3: j takes 0, 1, 2 → prints 3*0 3*1 3*2. Full marks awarded when showing the row-by-row iteration table!

Q2: Differentiate between *args and **kwargs with suitable code. (6 Marks)

Answer Strategy: State that *args receives arbitrary positional arguments as a tuple, whereas **kwargs receives arbitrary keyword arguments as a key-value dictionary. Provide a clean function that prints type(args) and type(kwargs) to prove their internal Python types.

📥 Printable Chapter Reference (PDF Supplement)

Prefer an offline physical copy for revision or exam night preparation? You can download our verified, printer-friendly PDF synthesis for Unit 3 below:

Python Programming: Unit 3 Control Structures & Loops Notes (PDF) Handwritten & typeset curriculum guide • Conditionals, Iterators, Functions & Solved PYQs
Download Printable PDF ↗

🔗 Related Study Resources