Python for Beginners

While in Python

Lesson 7 explains the while loop in Python: repetition logic, counters and accumulators, break and continue, and how to recognize and avoid infinite loops, with practical examples.

joao • 01 Nov 2026 • 5 min read • 287 • 0
While in Python | Usando Python
Publicidade

By the end of this lesson, you should understand the logic of loops, be able to use while with counters and accumulators, control execution with break and continue, and recognize the situations that lead to an infinite loop.

1. Loop logic

Up to this point, every program we wrote executed each line once, or made decisions with if. But there are situations where we need to repeat a block of code several times. For example: asking for a password until the user gets it right, adding numbers until the user types zero, or processing a list of items until the end.

Instead of duplicating lines of code, we use loops. In Python, the while loop runs a block as long as a condition is true.

The syntax is similar to if:

while condition:
    block_of_code

The difference is that if checks the condition once. while checks the condition before each repetition. If the condition is true, the block runs and the flow returns to the top of the while, where the condition is checked again. When the condition becomes false, the loop ends and the program continues on the next line.

The while flow:

  1. Evaluate the condition.

  2. If it is True, run the block.

  3. Return to step 1.

  4. If it is False, exit the loop and continue the program.

2. Counter and accumulator

Two patterns appear frequently when working with while: the counter and the accumulator.

Counter

A counter is a variable that records how many times something happened. It is usually initialized to 0 and incremented inside the loop.

counter = 0

while counter < 5:
    print(f"Count: {counter}")
    counter += 1

The output will be:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

Important note: when the loop ends, counter is 5. The check is made before each iteration, so the last run happens with counter == 4.

Accumulator

An accumulator is a variable that sums values over the loop. It is usually initialized with the neutral element of the operation — 0 for addition, 1 for multiplication.

total = 0
number = 1

while number <= 10:
    total += number
    number += 1

print(f"Sum from 1 to 10: {total}")   # 55

In this example, number is the counter and total is the accumulator. They work together: one advances the count, the other accumulates the result.

A common pattern: user input

total = 0

while True:
    entry = input("Enter a number (0 to exit): ")
    if entry == "0":
        break
    total += float(entry)

print(f"Total: {total}")

Here the loop is intentionally infinite (while True), and the exit depends on an internal condition with break. We will look at this pattern in detail in the next section.

3. break and continue

Python offers two instructions to control the flow inside a loop.

break — exit the loop immediately

The break instruction ends the loop right away, ignoring any remaining condition. The program continues on the line after the loop.

counter = 0

while True:
    print(counter)
    counter += 1
    if counter == 3:
        break

print("End")

The output will be:

0
1
2
End

continue — skip to the next iteration

The continue instruction interrupts only the current iteration. The flow returns to the top of the loop, where the condition is checked again.

counter = 0

while counter < 5:
    counter += 1
    if counter == 3:
        continue
    print(counter)

The output will be:

1
2
4
5

The 3 was skipped. Note that the increment happens before continue. If it were after, the counter would never reach 4 and the program would enter an infinite loop. This is a common pitfall.

Practical difference

  • break ends the loop. Nothing else inside it is executed.

  • continue only skips the rest of the current iteration and returns to the top.

4. Beware of the infinite loop

An infinite loop happens when the while condition never becomes false. This freezes the program, and the terminal gets stuck until you interrupt it manually — usually with Ctrl + C.

Example of an infinite loop

counter = 0

while counter < 5:
    print(counter)
    # we forgot to increment the counter

counter stays at 0, the condition counter < 5 is always true and the print runs forever.

Common causes

  • Forgetting to update the condition variable. In the example above, counter += 1 is missing.

  • Updating the variable in the wrong place. Incrementing only inside an if that may not run.

  • Using continue before updating the variable. It returns to the top without progress.

  • Comparing with != without ensuring the value will be reached.

number = 0
while number != 5:
    number += 2   # will never equal 5

This loop starts at 0, goes to 2, 4, 6, 8... it never hits 5 and never ends.

How to prevent it

  1. Always identify what makes the condition change. If nothing inside the loop affects the condition, it is an infinite loop.

  2. Prefer comparisons with < and > instead of != when the increment may skip the target value.

  3. Use while True with an explicit break when you want a loop controlled by an internal condition. This way the exit is visible.

  4. Test with small values. If the program loops with n = 5, it probably loops with n = 100000 too.

How to interrupt an infinite loop

In the terminal, press Ctrl + C. This sends an interrupt signal and ends the process. In environments like VS Code, there is a stop button next to the terminal.

Lesson wrap-up

In this lesson, you understood the logic of the while loop, learned to use counters and accumulators, saw how to control the flow with break and continue, and understood how to avoid — and interrupt — an infinite loop.

while is a powerful tool, but it requires attention. The golden rule is: inside the loop, something must change so that the condition eventually becomes false. If you cannot point to that change, the loop is a candidate for infinite.

In the next lesson, we will look at the for loop, which is more appropriate for iterating over known sequences and avoids several of the pitfalls of while.

Suggested exercise

Ask the user for integer numbers in sequence until they type 0. At the end, display:

  1. The sum of all numbers entered (excluding 0).

  2. The number of numbers entered.

  3. The average of the numbers entered (be careful with division by zero if no number was entered).

Hint: use a while True with break on the input, a counter for the quantity and an accumulator for the sum. Check the case where no number was entered before calculating the average.

📄 Copyright: Unless otherwise noted, all articles are original. Please cite the source when sharing.

🔗 Link: http://usandopy.com/en/python-para-iniciantes/while-em-python/

Publicidade
Você ainda não está logado, por favor faça login ou registre-se para comentar
    0 pessoas participaram | 0 comentários
    Ainda não há comentários, fique à vontade para conversar!