smartyfy.mrindigi.com

Python Master Course V2 — 023. While Loops

SMARTYFY ACADEMY · MODULE 03 · LESSON 023 OF 200

While Loops

Estimated study: 60–90 minutes · Prerequisite: Lesson 022 and preceding Python foundations.

Use condition-controlled repetition and explicit termination.

Video lesson

Video not available yet. This position is reserved for a verified lesson video link or player. The written lesson can be completed without it.

Learning outcomes

  • Explain use condition-controlled repetition and explicit termination.
  • Trace program state and predict the output.
  • Recognize common errors and boundary conditions.
  • Apply the concept to a complete practical project.
  • Write independent tests and justify results.

Understand the technique

Repeat while a condition stays true

A while loop is useful when a condition determines whether another attempt is needed: waiting for a valid menu choice, counting down remaining work, or accepting entries until a sentinel is entered. A sentinel is a special value that means “stop”; it is not part of the data being processed. Prefer a for loop when the task is simply to visit every item in an existing collection.

Python checks the condition before every iteration, including the first. If it is false immediately, the body runs zero times. After the final indented statement, control returns to the condition. The first unindented statement after the loop runs only once, after the condition becomes false.

Trace the state, not just the printed lines

remaining = 3
while remaining > 0:
    print("Remaining:", remaining)
    remaining -= 1
print("Start")

Expected output

Remaining: 3
Remaining: 2
Remaining: 1
Start

On the first check, 3 > 0 is true. Printing does not change the counter; the subtraction does. The next checks see 2, then 1, then 0. Zero fails the condition, so the loop does not print “Remaining: 0”. Starting at zero also prints only “Start”. Moving the final print into the indented body would change both its timing and how often it appears.

Before writing a condition-controlled loop, identify four things: its starting state, its continuation condition, the update that moves toward stopping, and the expected final state. Here the counter decreases by one on every path through the body. A decreasing nonnegative counter gives a simple explanation of why this loop finishes.

Guided task: accept a bounded number of menu attempts

This small menu accepts start, allows quit as a sentinel, and permits at most three unsuccessful entries. Leading and trailing spaces and letter case are normalized. Any other text is invalid. The boolean finished records whether a recognized choice has been received; it prevents another prompt after either recognized choice.

Run this interactive menu in a local Python terminal so you can type responses at each prompt.

attempts = 0
finished = False
while attempts < 3 and not finished:
    choice = input("Type start or quit: ").strip().casefold()
    attempts += 1
    if choice == "start":
        print("Starting")
        finished = True
    elif choice == "quit":
        print("Cancelled")
        finished = True
    else:
        print("Invalid choice")
if not finished:
    print("Attempt limit reached")

Sample interaction (the words after each prompt are typed by the learner)

Type start or quit: later
Invalid choice
Type start or quit: START
Starting

The attempt counter increases for every response, so an invalid response still moves toward termination. Three invalid responses produce three “Invalid choice” lines followed by “Attempt limit reached”. Entering quit first produces “Cancelled” and no further prompt. This is a menu exercise, not an authentication or security mechanism.

Spot a loop that cannot make progress

If the countdown subtracts zero, subtracts outside the body, or accidentally increases the counter, its condition may never become false. Stop an accidentally endless local program with your editor’s Stop control or Ctrl+C in the terminal, then inspect the update. A loop can also be correctly waiting inside input(); no new output while a prompt awaits your response does not by itself mean the loop is broken.

For the menu task, test immediate success, immediate cancellation, mixed invalid and valid entries, and three invalid entries. Record the number of prompts as well as the final message. That checks termination, not merely whether one expected word appeared.

Runnable example and expected output

Setup: Python 3.10 or newer, standard library only. Save the following as lesson_023.py and run python lesson_023.py (or python3).

counter=1
while counter<=3:
    print(counter)
    counter+=1

Expected output:

1
2
3

Walkthrough: Identify the initial variable values, follow the control flow in execution order, and write down every printed result. Change one input, predict the new output and then run the modified program.

Introductory project: countdown trace

Seconds is a validated nonnegative integer. This helper demonstrates state changes and termination; the bounded menu above is the practical extension.

This project applies while loops to a practical scenario. Review the input values and decision or iteration rule before running the program.

def countdown(seconds):
    while seconds>0:
        print(seconds)
        seconds-=1
    print("Start")
countdown(3)

Expected output:

3
2
1
Start

Testing plan: Run the shown sample, add an empty or minimum-size input where applicable, and test a value at the relevant boundary. For larger systems, separate the core calculation from user input so it can be tested independently.

Common mistakes and professional practices

  • Confusing an expression’s value with a side effect.
  • Skipping validation of inputs and collection sizes.
  • Misreading the order of operations or changes to state.
  • Forgetting to test zero, empty, minimum and maximum cases.
  • Using overly complicated logic instead of descriptive intermediate variables.

Debugging approach: Print the relevant state, compare each step with the expected result, isolate the first divergence, correct the underlying rule, and rerun all cases.

Think, trace, and solve

Attempt each question before revealing its answer. Explain your reasoning as well as the final result.

1. Can the body run zero times?

value = 5
while value < 3:
    print(value)
    value += 1
print("Finished", value)

Predict every printed line.

Need a hint?

Evaluate the first condition before tracing any statement inside the body.

Reveal answer and reasoning

Expected output

Finished 5

The first condition is false. Neither the print nor the update inside the body runs, so value remains 5.

2. Follow a changing condition

balance = 7
while balance > 2:
    print(balance)
    balance -= 3
print("Left:", balance)

What is printed, and why is 1 not printed inside the loop?

Reveal answer and reasoning

Expected output

7
4
Left: 1

The updates change 7 to 4 and then 1. The condition is checked again before printing; 1 is not greater than 2.

3. Repair the missing progress

Reading fragment: This deliberately broken loop never updates count. Inspect it without executing it.

count = 1
while count <= 3:
    print(count)
count += 1

Why does this loop keep printing 1? Show the repair without changing the condition.

Reveal answer and reasoning
count = 1
while count <= 3:
    print(count)
    count += 1

The original update is outside the loop and cannot be reached while the condition stays true. Indenting it changes count on every iteration, producing 1, 2, and 3 on separate lines.

4. Test the final allowed attempt

In the menu exercise, the user enters later, maybe, then start. Does “Attempt limit reached” appear? Explain the final values of both state variables.

Reveal answer and reasoning

No. The third attempt is allowed because the condition is checked while attempts is still 2. The response makes attempts equal 3 and finished equal True, and “Starting” is printed. The final if not finished is false.

5. Choose a termination rule

You need to read daily amounts until the user types done. Why is “repeat exactly seven times” a different requirement? What must happen after an invalid entry?

Reveal answer and reasoning

A sentinel-controlled loop allows the user to finish after any number of amounts, including zero. Seven fixed repetitions would require seven attempts regardless of whether the user had more or fewer amounts. After invalid text, report the problem and obtain fresh input; repeatedly checking the same unchanged invalid value cannot make progress. If retries must also be bounded, count invalid responses toward an explicit limit.

Further challenge

  • Advanced challenge: Add a new business rule, provide three test cases and explain the expected result for each.

Mastery checkpoint

Before advancing, explain the main concept without notes, predict the example output, run the project, and create at least three independent tests. If your results differ, revisit the debugging section.

Summary: Use condition-controlled repetition and explicit termination. Reliable programs combine clear logic, appropriate validation and repeatable testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.