Python Loops: for and while Explained

Published on: July 10, 2026
Reading time: 5 minutes
Símbolo de repetição ao lado do logotipo do Python pensativo, representando o conceito de loops na programação em Python.

Python loops repeat a block of code without requiring you to write the same instructions again and again. They are used to process lists, read files, validate input, create menus, calculate totals, and automate repetitive tasks.

Python has two main loop structures: for and while. This guide explains how each one works, when to choose it, and how to use range(), break, continue, else, enumerate(), zip(), nested loops, and practical patterns safely.

Review Python data types and the in operator if collections and membership are still new.

What Is a Loop?

A loop executes an indented code block repeatedly. The repetition may happen once for every item in a collection or while a condition remains true.

The official Python control flow tutorial covers loops and related statements. The range documentation defines numeric sequence behavior.

The for Loop

A for loop iterates over an iterable such as a list, tuple, string, dictionary, set, range, or file.

languages = ["Python", "JavaScript", "Go"]

for language in languages:
    print(language)

On each iteration, language receives the next value. The loop ends when there are no more items.

Loop Over a String

for character in "Python":
    print(character)

Strings are iterable, so each iteration returns one character.

Use range()

range() generates integer values lazily:

for number in range(5):
    print(number)

The output is 0 through 4. The stop value is excluded.

for number in range(2, 11, 2):
    print(number)

This starts at 2, stops before 11, and advances by 2.

Calculate a Total

prices = [19.90, 35.50, 12.00]
total = 0

for price in prices:
    total += price

print(f"Total: {total:.2f}")

Python also provides sum(prices), which is clearer for simple totals. Loops are useful when each item needs additional validation or transformation.

Use enumerate() for Indexes

Avoid manually updating an index variable:

tasks = ["Study loops", "Write code", "Run tests"]

for position, task in enumerate(tasks, start=1):
    print(f"{position}. {task}")

The enumerate guide includes files, custom start values, and combined loops.

Loop Over Dictionaries

student = {
    "name": "Maya",
    "course": "Python",
    "active": True,
}

for key, value in student.items():
    print(f"{key}: {value}")

Iterating directly over a dictionary returns its keys. Use items() when you need both keys and values.

Loop Over Multiple Collections with zip()

names = ["Alex", "Sam", "Maya"]
scores = [85, 92, 88]

for name, score in zip(names, scores):
    print(f"{name}: {score}")

By default, zip() stops when the shortest iterable ends. Validate lengths when missing data would be a problem.

The while Loop

A while loop repeats while its condition is true:

count = 1

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

The condition must eventually become false. Forgetting count += 1 would create an infinite loop.

Input Validation with while

while True:
    text = input("Enter a positive integer: ")

    if text.isdigit() and int(text) > 0:
        number = int(text)
        break

    print("Invalid value. Try again.")

print(f"You entered {number}.")

while True is appropriate when the stopping point depends on an event inside the loop.

Use break

break immediately exits the nearest loop:

numbers = [4, 8, 15, 16, 23, 42]
target = 15

for number in numbers:
    if number == target:
        print("Target found")
        break

Only the innermost loop is affected when loops are nested.

Use continue

continue skips the rest of the current iteration:

values = [10, -2, 7, -5, 3]

for value in values:
    if value < 0:
        continue

    print(value)

Use it sparingly. A clear condition around the main logic is sometimes easier to read.

The Loop else Clause

A loop’s else block runs when the loop ends normally, not when it exits through break.

numbers = [4, 8, 15, 16]
target = 23

for number in numbers:
    if number == target:
        print("Found")
        break
else:
    print("Not found")

This pattern is useful for searches and validation.

Nested Loops

for row in range(1, 4):
    for column in range(1, 4):
        print(f"({row}, {column})")

The inner loop completes for every iteration of the outer loop. Three rows multiplied by three columns produce nine iterations.

Create a Multiplication Table

for row in range(1, 6):
    line = []

    for column in range(1, 6):
        line.append(f"{row * column:2}")

    print(" ".join(line))

Nested loops are useful for grids, tables, matrices, and game boards, but their work grows quickly as input sizes increase.

Loop Through a File

from pathlib import Path

file_path = Path("events.txt")

with file_path.open(encoding="utf-8") as file:
    for line_number, line in enumerate(file, start=1):
        cleaned = line.strip()

        if cleaned:
            print(line_number, cleaned)

Iterating directly over the file processes one line at a time and is suitable for large text files. See the text files guide.

List Comprehensions

A simple loop that builds a list can sometimes become a comprehension:

squares = []

for number in range(1, 6):
    squares.append(number ** 2)

# Equivalent concise form
squares = [number ** 2 for number in range(1, 6)]

Use the regular loop when the logic requires several steps, error handling, or side effects. The list comprehensions guide explains filters and readability limits.

Modify Collections Safely

Removing items from a list while iterating over the same list can skip values:

numbers = [1, 2, 3, 4, 5, 6]

# Safer: build a new list
numbers = [number for number in numbers if number % 2 != 0]
print(numbers)

When mutation is required, iterate over a copy or clearly separate reading from modification.

Practical Project: Expense Summary

expenses = [
    {"category": "Food", "amount": 24.50},
    {"category": "Transport", "amount": 15.00},
    {"category": "Food", "amount": 32.90},
    {"category": "Books", "amount": 45.00},
]

totals = {}

total_spent = 0
for expense in expenses:
    category = expense["category"]
    amount = expense["amount"]

    total_spent += amount
    totals[category] = totals.get(category, 0) + amount

print(f"Total spent: {total_spent:.2f}")

for category, amount in sorted(totals.items()):
    print(f"{category}: {amount:.2f}")

The project combines a list of dictionaries, accumulation, dictionary lookup, and a final reporting loop. For more sorting options, read sort() vs sorted().

Practical Project: Limited Guessing Game

import random

secret = random.randint(1, 20)
maximum_attempts = 5

for attempt in range(1, maximum_attempts + 1):
    try:
        guess = int(input(f"Attempt {attempt}: "))
    except ValueError:
        print("Enter a whole number.")
        continue

    if guess == secret:
        print("Correct!")
        break

    if guess < secret:
        print("Too low.")
    else:
        print("Too high.")
else:
    print(f"No attempts left. The number was {secret}.")

This combines for, continue, break, and loop else. The random module guide explains random number generation.

Avoid Infinite Loops

Before writing a while loop, answer three questions:

  • What condition starts as true?
  • What changes during every relevant iteration?
  • What event makes the condition false or triggers break?

When a loop never ends, interrupt it in a terminal with Ctrl+C and inspect its condition and update logic.

Common Mistakes

  • Forgetting indentation.
  • Expecting range(5) to include 5.
  • Forgetting to update a while condition.
  • Using break when continue was intended.
  • Modifying a list while iterating over it.
  • Using manual indexes instead of enumerate().
  • Creating deeply nested loops without considering the amount of work.
  • Using a comprehension for logic that is too complex to read.

Frequently Asked Questions

What is the difference between for and while?

for iterates over items. while repeats based on a condition.

Can a loop run zero times?

Yes. A for loop over an empty iterable and a while loop with an initially false condition do not execute their bodies.

Does break exit every nested loop?

No. It exits only the nearest loop. Use a function, flag, or other control structure when several levels must stop.

Is a list comprehension always faster?

It may be efficient for simple transformations, but readability and correctness should guide the choice.

Conclusion

Use for to process iterables and while when repetition depends on a changing condition. Add enumerate() for indexes, zip() for parallel collections, and break or continue only when they make the flow clearer.

The best way to learn loops is to predict each iteration before running the code. Trace variable values on paper, then compare your prediction with the output.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    texto 'operadores em Python' com os simbolos de operadores e o logo do Python à direita
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Operators: Types and Practical Examples

    Learn Python operators with arithmetic, comparison, assignment, logical, membership, identity, bitwise, set, and conditional examples, plus precedence and common mistakes.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    texto 'None' centralizado com um fundo com as cores do Pyton
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python None Explained: Meaning and Best Practices

    Learn what Python None means, how to compare it correctly, use optional returns and defaults, distinguish missing values, work with

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Ilustração representando conjuntos (sets) em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Sets: Complete Beginner Guide

    Learn Python sets from scratch: unique values, membership, add and remove methods, union, intersection, differences, subsets, comprehensions, frozenset, and practical

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Programador resolvendo problemas com Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Programming Logic with Python for Beginners

    Learn programming logic with Python using algorithms, pseudocode, input and output, conditions, loops, functions, data structures, validation, testing, and a

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Código Python com valores Boolean True e False em tela de computador
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Booleans: True, False, and Logic

    Learn Python booleans with True and False, comparison and logical operators, truthy and falsy values, identity, membership, short-circuiting, and validation.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Código Python mostrando uma função recursiva de fatorial com condição if e chamada da função dentro dela
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Recursion: Beginner Guide with Examples

    Learn Python recursion with base cases, recursive calls, stack behavior, factorial, Fibonacci, trees, directories, memoization, limits, and when loops are

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026