Lecture-16 Iteration while Python 24-25

COMP101 Introduction to Programming 2024-25 Lecture-16: Iteration with while in Python

Overview of While Loop

  • Definition: A non-deterministic loop where the end condition is unknown until evaluated.

  • Control Mechanism: The loop starts with a test condition, tested for True/False values.

  • Execution Flow:

    • Start loop execution while the condition is True.

    • Exit the loop when the condition turns False.

    • Test condition must eventually change to ensure loop termination.

Structure of While Loop

  • Syntax:

    while CONDITION:
        <STATEMENTS>
  • Example:

    i = 0
    while (i < 5):
        i = i + 1
        print(i)
    print("loop ended")
  • Key Points:

    • Use a sentry variable initialized close to the loop’s entry point (0 for numbers, space for strings).

    • Modify the sentry variable within the loop to prevent infinite loops.

    • The first line aligned with the 'while' indicates the loop's termination.

Common Errors in While Loops

Infinite Loops
  • Example:

    name = input("Enter your name: ")
    onScreen = input("Want to see your name on screen? Y/N: ")
    onScreen = onScreen.upper()
    while onScreen == "Y":
        print(name)
        print()  # helps with readability
    print("Loop end")
  • Issue: If the sentry variable isn't updated within the loop, it leads to an infinite loop.

  • Resolution:

    • Re-prompt for user input within the loop to avoid continuous output.

Logic Errors
  • Example:

    lives_left = 7
    while lives_left != 0:
        print("Hero is hurt in battle - lose 3 lives")
        lives_left = lives_left - 3
        print("Hero has", lives_left, "lives left")
    print("Hero has no lives remaining")
    print("Loop end")
  • Issue: Subtracting 3 repeatedly from an initial value of 7 doesn’t provide a terminating condition.

  • Resolution: Change the initialization (set to multiple of 3) or adjust the loop condition for greater than checks.

Correcting Logic Errors in Output

  • Initial Error:

    i = 0
    while i <= 5:
        i = i + 1
        print(i)
  • Issue: Loop outputs 0 to 6 instead of 1 to 5.

  • Correction:

    • Initialize the variable to 1, really start counting from there.

    i = 1
    while i <= 5:
        print(i)
        i += 1
    • New Output: Correct range of 1 to 5.

Construction of While Loops in Menu Systems

Requirement
  • Access a program via a main menu.

  • Single entry and exit via the main menu.

Steps to Implement Menu
  1. Output Menu:

    print("Main Menu")
    print("A: Option-A code")
    print("B: Option-B code")
    print("C: Option-C code")
    print("X: Exit")
  2. User Input:

    • Capture user option and handle invalid inputs gracefully.

  3. Selection Logic:

    if option == "A":
        print("Option-A under development")
    elif option == "B":
        print("Option-B under development")
    elif option == "C":
        print("Option-C under development")
    else:
        print("Program ended")
  4. Iteration Construct:

    while option not in "X":
        [menu code]
    • Continues until user opts to exit.

Program Usability Enhancements

  • Cosmetic changes

    • Use whitespace for readability.

    • Clear output to the user upon interactions.

    • Example: Keep outputs held on screen using input() before returning to the menu.

Testing While Loops

  • Checklist:

    • Ensure the loop body executes at least once.

    • Verify the test condition will eventually be met.

    • Review statements order in loop body and initialization of control variables.

Summary of while Loop Characteristics

  • Basic structure is: while (test = T): executes the loop body.

  • Can support nested constructs like: while-else, break, continue.

  • Reminder: The test must be refreshed in the loop to allow for re-evaluation at the next iteration.