RizTech Academy logo
RizTech Academy
Control FlowLesson 4 of 615 min

while loops, and how to avoid infinite ones

A for loop runs once per item and you know the count before it starts. A while loop runs as long as something stays true, and you may have no idea how many times that will be.

The shape

count = 1

while count <= 5:
    print(count)
    count += 1
1
2
3
4
5

Python checks the condition, runs the block if it is true, then goes back and checks again. When the condition becomes false, the loop ends and the program carries on.

Three parts have to be right, and they are the whole lesson:

  1. Set something up before the loop — count = 1
  2. A condition that can become false — count <= 5
  3. Something inside that moves towards that — count += 1

Miss the third and the loop never ends.

Infinite loops

count = 1

while count <= 5:
    print(count)
    # forgot count += 1

This prints 1 forever. Your terminal fills, your fan spins up, and nothing stops on its own.

Press Ctrl + C to stop it. That sends an interrupt and Python quits with a KeyboardInterrupt. Learn that shortcut now — you will need it today.

The subtler version passes the eye test:

count = 10

while count > 0:
    print(count)
    count += 1      # should be -= 1

The condition is sensible, there is an update, and it still runs forever because the update moves the wrong way. When a loop hangs, check that the update actually moves towards the exit.

When to use which

Use for when you are walking a collection or repeating a known number of times. That is most loops.

Use while when the end depends on something you cannot know up front:

  • reading until the user types quit
  • retrying until a request succeeds
  • continuing until a calculation is close enough
  • running a game until somebody wins

If you find yourself writing a while with a counter you increment by hand, that is almost always a for loop wearing a disguise.

Validating input

The most common genuine use for while in a small program — keep asking until the answer makes sense:

age = input("Enter your age: ")

while not age.isdigit():
    print("Please enter a whole number.")
    age = input("Enter your age: ")

age = int(age)
print(f"You are {age}.")

It repeats until the input is usable, and by the time the loop exits you can convert with confidence.

The duplicated input(...) on two lines is slightly awkward. The usual fix:

while True:
    age = input("Enter your age: ")
    if age.isdigit():
        break
    print("Please enter a whole number.")

age = int(age)

while True is a deliberately infinite loop with break as the exit. That sounds alarming and is completely standard — it reads better than repeating the prompt, and break is covered properly in the next lesson.

A menu loop

The same shape drives most small interactive programs:

running = True

while running:
    print("\n1. Say hello")
    print("2. Say goodbye")
    print("3. Quit")

    choice = input("Choose: ").strip()

    if choice == "1":
        print("Hello!")
    elif choice == "2":
        print("Goodbye!")
    elif choice == "3":
        running = False
    else:
        print("I did not understand that.")

print("Bye.")

A boolean controlling the loop — often called a flag — is clear and easy to extend. Setting running = False does not stop the loop immediately: the rest of the block still runs, and the condition is only rechecked at the top.

Accumulating until a condition

target = 1000
balance = 100
rate = 0.10
years = 0

while balance < target:
    balance = balance * (1 + rate)
    years += 1

print(f"It took {years} years to reach {balance:.2f}")
It took 25 years to reach 1083.47

This is the genuine while case. You could not have written for year in range(25) because 25 is the answer, not the input.

Two things to be careful about

Floating point conditions. Remember 0.1 + 0.2 from the numbers lesson:

value = 0.0
while value != 1.0:      # may never be exactly 1.0
    value += 0.1

This can run forever. Use < rather than != when floats are involved:

while value < 1.0:
    value += 0.1

Reading a variable the loop never sets. If the condition is false on the very first check, the block never runs at all:

items = []
index = 0

while index < len(items):
    print(items[index])
    index += 1

print("done")

That prints only done, which is correct. But if you expected the loop to define something for use afterwards, it did not.

Stopping a runaway loop in your own code

While you are still learning, a guard is a reasonable safety net:

attempts = 0

while not finished and attempts < 100:
    ...
    attempts += 1

If the logic is wrong, you get a loop that ends rather than a hung terminal. This is a real technique in production code too, where it is called a retry limit — a program that waits forever for something that will never happen is worse than one that gives up and says so.

Practice

  1. Print 10 down to 1 using while, then Liftoff! afterwards.
  2. Write a loop that keeps asking for a password until the user types python123, then prints Access granted.
  3. Write the input validation loop for age, and check it handles abc, an empty input, and 25.
  4. Starting with balance = 5000 and 7% annual interest, find how many years until it passes 10,000.
  5. Build the menu loop above, then add a fourth option that counts how many times it has been chosen.
  6. Write an infinite loop on purpose. Stop it with Ctrl + C. Read the KeyboardInterrupt message. Do this once so it is never frightening.
  7. Take the while count > 0 example with count += 1 and, without running it, explain in one sentence why it never ends.

Next: break, continue, and a loop feature most Python developers have never knowingly used.

Stuck on this lesson?

Being stuck is part of it — but being stuck alone for three days is not. Our internship programme pairs this curriculum with code review and one-to-one help from working developers, and it is free.

About the internship