Lecture-17_3 Iteration Python - nested for 24-25

COMP101 Introduction to Programming: Iteration and Nested Loops

Nested Loops Overview

  • Definition: A loop (for or while) can contain other loops within its body.

    • Types of Nested Loops:

      • For loop within a for loop

      • For loop within a while loop

      • While loop within a while loop

      • While loop within a for loop

    • Selection statements can be included within loops.

Structure of Nested Loops

  • Outer Loop: The loop which encloses another loop or condition (if).

  • Inner (Nested) Loop: The loop contained within the outer loop.

    • The outer loop controls the number of iterations of the inner loop.

    • The inner loop executes with each iteration of the outer loop.

Indentation in Nested Loops

  • Indentation in Python is critical as it defines the start and end of loops:

    • Format:

      • Outer loop start (header)

      • Outer loop statements (if any)

      • Inner loop start (header)

      • Inner loop statements (mandatory)

      • Inner loop ends with un-indented line

      • Outer loop ends with un-indented line

Example: Nested For Loop Structure

  • Outer Loop: for i in range(0,2)

    • Iterates twice with the indices [0] and [1].

    • On each iteration, prints the outer loop index and executes inner loop.

  • Inner Loop: for j in range(10,13)

    • Iterates three times for indices [10], [11], [12].

    • On each iteration, prints the inner loop index.

  • Return to outer loop for next iteration.

Problem Statement: Multiplication Tables

  • Produce '2-times' and '3-times' tables.

  • Output Format:

    • Multiplier (2 and 3) * Multiplicand (1 to 10) = Product.

  • Design Principles:

    • Outer loop iterates twice for 2-times and 3-times tables (deterministic).

    • Inner loop iterates ten times to print each multiplication result.

Mechanics of Execution

  1. Outer loop iterates first with multiplier = 2.

  2. Inner loop iterates ten times to print the 2-times table.

  3. Outer loop iterates again with multiplier = 3.

  4. Inner loop iterates ten times to print the 3-times table.

  5. Program concludes after printing all required tables.

Pseudocode Structure

  1. Initialization:

    • Set first_value = 2

    • Set second_value = 3

  2. Loop Structure:

    • Outer loop iterates over first_value and second_value.

      • Inner loop executes ten times to print multiplication results.

Practical Example of Nested Loop in Python

num_of_tables = int(input("How many tables to print? "))
for i in range(1,num_of_tables + 1):  # Outer loop
    print("Printing the", i, "times table")
    for j in range(1,11):  # Inner loop
        print(i, '*', j, '=', i*j)
    print()  # Blank line between tables

User Control and Flexibility in Design

  • Users can determine:

    • Number of multiplication tables.

    • Number of multiplicands per table.

  • Changes to num_of_tables and num_of_mults affect the output and execution flow.

Nested Loops with Inputs from Users

  • Detailed Steps:

    • Gather input for number of students and assignments per student.

    • Loop through students (outer) and grades (inner) to capture input.

    • Each iteration captures an individual student's grades and stores them accordingly.

Special Cases: Nested While Loops and Conditions

  • When not all submissions are mandatory:

    • Use a while loop to handle varying numbers of submissions.

  • Example code structure:

for i in range (1, students + 1):
    print("This is student", i)
    submission = input("Is there a submission for this student y/n: ")
    while submission == 'y':
        grade = int(input("Enter grade for student:"))
        submission = input("Is there a submission for this student y/n: ")
print('All processed')

Nested Loop with Conditionals

  • Use of if statements to classify numbers as even or odd within a nested structure.

for i in range(6):
    print(i)
    if i % 2 == 0:
        print(i,"is an even number")
    else:
        print(i,"is an odd number")
print()  # End loop

Loop Control Statements: Break and Continue

  • Break: Exits a loop immediately when a condition is met.

  • Continue: Skips the current iteration and proceeds to the next.

  • Example for break:

for mushroom in partyFoodList:
    if mushroom == "LILAC":
        break

Advanced Nested Loops: Pass and Else

  • Pass statement used as a placeholder in loops and conditions. Allows code to be structured without active implementation.

  • Use of for-else: Executes a block after the loop unless interrupted by a break.

for i in range(1, 11):
    if i <= 0:
        print(i,"is -ve")
        break
    else:
        print(i,"is +ve")
else:
    print("all numbers processed")

Conclusion

  • Maximum nesting levels in Python is recognized up to 20.

  • Properly understand design implications to manage complexity within loops.

  • Ensure to structure nested loops and break/continue effectively to minimize side effects.