Skip to Content
Course content

53: While Loops and Loop Control

Click on the "Edit" button in the top corner of the screen to edit your slide content.

We've spent a lot of time with for loops, which are great when you know exactly how many items you're dealing with. But in the real world, you often don't know when a task will end. Maybe you're waiting for a user to type "quit," or you're polling an API until a status changes to "complete." For that, we need the while loop.

Wait, why is my terminal frozen?

Let's try to build a simple command-line interface. I want a program that just keeps asking me for a command until I tell it to stop. I'll start with the most basic while loop possible.

while True:
    command = input("Enter a command: ")
    print(f"Executing {command}...")

If I run this, it works... too well. It asks for a command, prints it, and then immediately asks again. And again. I've just created an infinite loop. Now I'm stuck hitting Ctrl+C to kill the process. The while True: pattern is incredibly common, but it's a dangerous tool if you don't have an exit strategy.

Finding the exit door

I need a way out. The most straightforward way is to change the condition from True to a variable that I can flip. Let's try using a boolean flag.

is_running = True

while is_running:
    command = input("Enter a command (type 'exit' to stop): ")
    if command == "exit":
        is_running = False
    else:
        print(f"Executing {command}...")

This works. It's safe. But honestly? It feels a bit wordy. I have to initialize a variable outside the loop and then update it inside. In a larger project, tracking the state of is_running across a hundred lines of code can get annoying. There's a cleaner way to just "bail out" of a loop immediately.

Cutting the line with break

Python gives us the break keyword. It tells the program: "Stop this loop right now and move to the next block of code below it." Let's rewrite that same logic without the flag.

while True:
    command = input("Enter a command (type 'exit' to stop): ")
    if command == "exit":
        break
    print(f"Executing {command}...")

print("Program shut down successfully.")

Much better. The logic is flatter and easier to read. The loop runs indefinitely until it hits that break statement, at which point it jumps straight to the final print statement.

Skipping the garbage

Now, here is a real-world problem: users are unpredictable. If I just hit Enter without typing anything, my current program says "Executing ...", which is silly. I don't want to stop the whole loop, but I do want to skip the "Executing" part for empty inputs.

I could wrap everything in an if/else, but that leads to "indentation hell" where your code keeps drifting to the right. Instead, I'll use continue. This tells Python to stop the current iteration and jump back to the top of the loop immediately.

while True:
    command = input("Enter a command (type 'exit' to stop): ")
    
    if command == "exit":
        break
    
    if not command:
        print("You didn't type anything! Try again.")
        continue
        
    print(f"Executing {command}...")

Notice how the continue prevents the print(f"Executing...") line from running. It effectively says, "This specific attempt was a waste of time; let's just start over from the top."




📋 Practical Task

Build a Limited-Attempt ATM Pin Validator

Write a program that simulates an ATM pin entry system. The goal is to protect the account by limiting the number of attempts.

  • Set a secret pin (e.g., "1234").
  • Give the user a maximum of 3 attempts to enter the correct pin.
  • Use a while loop to keep asking for the pin.
  • If the user enters the correct pin, print "Access Granted" and use break to exit the loop.
  • If the user enters the wrong pin, decrement their remaining attempts and tell them how many tries they have left.
  • If the user runs out of attempts, the loop should end and print "Account Locked."
Rating
0 0

There are no comments for now.

to be the first to leave a comment.