Python For and While Loops: Master Repetition in Python

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Python Loop Basics

Loops are a fundamental building block of any algorithm in programming. They allow you to execute the same block of code multiple times, making your programs far more efficient. In Python, there are two main types of loops, each with its own use cases and syntax.

Types of Loops in Python

Python gives developers two primary loop structures. The for loop is used when you know the number of repetitions in advance or need to iterate over a sequence of items. The while loop keeps running as long as a specific condition is true.

A deep understanding of how loops work is key to effective Python programming. Using loops correctly helps you write cleaner, faster, and more scalable code.

The Python for Loop

Syntax and Core Concepts

The basic structure of a Python for loop looks like this:

for variable in sequence:
    # loop body

The Python for loop iterates over every item in any iterable object. This includes lists, strings, tuples, dictionaries, sets, and special range objects.

Working with the range() Function

The range() function is a built-in tool for generating sequences of numbers. It's especially useful when you need a loop with a fixed number of iterations.

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

Output:

0
1
2
3
4

Advanced range() Features

The range() function accepts three parameters: start, stop, and step. The full syntax is:

range(start, stop, step)

Example with a negative step:

for i in range(10, 0, -2):
    print(i)

This code prints: 10, 8, 6, 4, 2.

Iterating Over Different Data Types

Working with Strings

A for loop makes it easy to go through each character in a string:

for char in "Python":
    print(char)

Each character is printed on its own line.

Processing Lists

Iterating over list items works the same way:

fruits = ["apple", "pear", "grape"]
for fruit in fruits:
    print(fruit)

Looping Through Dictionaries

When working with dictionaries, you can loop through keys, values, or key-value pairs:

data = {"name": "Anna", "age": 25, "city": "Moscow"}
for key, value in data.items():
    print(f"{key} = {value}")

Dictionary iteration methods:

  • keys() - returns the keys
  • values() - returns the values
  • items() - returns key-value pairs

The Python while Loop

Syntax and How It Works

The while loop has a simpler structure than the for loop:

while condition:
    # loop body

The loop keeps running as long as the given condition is True. Once the condition becomes False, the loop stops.

Practical Examples

Simple Counter

i = 0
while i < 5:
    print(i)
    i += 1

Output: numbers from 0 to 4.

Handling User Input

The while loop is often used to validate user input:

password = ""                

Blogs

Book Recommendations