Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 4 · While Loops

While Loops

On this pageBasic ExampleExample with User InputUsing break and continueMini Project — Number Guessing Game

A while loop repeats a block of code as long as a given condition remains true. It is especially useful when the number of repetitions is not known in advance. For example, it is used to wait for user input or process data until a certain value is reached.

Basic Example

Let’s start with a simple counter:

count = 1

while count <= 5:
    print("Count:", count)
    count += 1

print("Loop finished.")
Listing 115 — Basic Example

Output

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop finished.

Here, Python checks the condition count <= 5 before every iteration.

The loop continues while it’s True, and stops when it becomes False.

Without updating count, the loop would run forever — so remember to include a statement that changes the condition inside the loop.

Example with User Input

While loops are especially useful for interactive programs that depend on user input. Let’s see an example where the program repeatedly asks the user for a password until they type the correct one.

# Ask for a password until the user enters the correct one
password = ""

while password != "python123":
    password = input("Enter the password: ")

print("Access granted!")
Listing 116 — Example with User Input

Example Run:

Enter the password: hello
Enter the password: 123
Enter the password: python123
Access granted!
Listing 117 — Example with User Input

Here, the loop keeps running as long as the password entered is not equal to "python123".

Once the user types the correct password, the condition becomes False and the loop exits.

Using break and continue

You can control how a loop behaves using two special keywords: - break — exits the loop immediately - continue — skips the rest of the loop body and moves to the next iteration

number = 0

while number < 10:
    number += 1
    if number == 5:
        continue  # skip printing 5
    if number == 8:
        break     # stop the loop at 8
    print(number)
Listing 118 — Using break and continue

Output

1
2
3
4
6
7

This example shows how to control a loop and skipping certain values or stopping early when needed.

Mini Project — Number Guessing Game

Let’s apply what we’ve learned about while loops to create a small interactive game.

Write a program that asks the user to guess a secret number between 1 and 10.

The program should keep asking until the user guesses correctly.

After each wrong guess, it gives a hint — “too high” or “too low.”

Example Run:

Guess a number between 1 and 10: 3
Too low! Try again.
Guess a number between 1 and 10: 9
Too high! Try again.
Guess a number between 1 and 10: 7
Congratulations! You guessed it right.
Listing 119 — Mini Project — Number Guessing Game