Cycles for and while in Python: how to work with repeats

онлайн тренажер по питону
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

Fundamentals of Python Loops

Loops are a fundamental element of any algorithm in programming. They provide the ability to execute the same block of code multiple times, which significantly increases program efficiency. In the Python programming language, there are two main types of loops, each with its own application features and syntax.

Types of Loops in Python

Python offers developers two primary types of loop constructs. The for loop is used in situations where the range of repetitions is known beforehand or when it's necessary to iterate over the elements of a sequence. The while loop continues to run as long as a specific condition is met.

A deep understanding of how loops work is a key factor for effective programming in Python. The correct use of loop constructs allows for the creation of more readable, high-performance, and scalable code.

The for Loop in Python

Syntax and Core Principles

The basic structure of a for loop in Python is as follows:

for variable in iterable:
    # loop body

The for loop in Python iterates over the elements of any iterable object. Such objects include lists, strings, tuples, dictionaries, sets, and special range objects.

Working with the range() Function

The range() function is a built-in tool for creating sequences of numbers. It is particularly useful for creating loops with a specified number of iterations.

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

Execution result:

0
1
2
3
4

Advanced range() Capabilities

The range() function supports three parameters: a start value, a stop value, and a step. The full syntax is as follows:

range(start, stop, step)

Example using a negative step:

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

This code will print the numbers: 10, 8, 6, 4, 2.

Iterating Over Different Data Types

Working with Strings

A for loop makes it easy to iterate over characters in a string:

for char in "Python":
    print(char)

Each character of the string will be printed on a new line.

Processing Lists

Iterating over list elements is done in a similar way:

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

Iterating Through Dictionaries

When working with dictionaries, you can iterate over keys, values, or key-value pairs:

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

Dictionary methods for iteration:

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

The while Loop in Python

Syntax and Principle of Operation

The while loop has a simpler structure compared to for:

while condition:
    # loop body

The loop continues to execute as long as the specified condition returns True. When the condition becomes false, the loop terminates.

Practical Examples

Simple Counter

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

Result: numbers from 0 to 4.

Handling User Input

The while loop is often used to validate user input:

password = ""
while password != "secret":
    password = input("Enter password: ")
print("Access granted")

Accumulating Data

total = 0
number = 1
while number <= 10:
    total += number
    number += 1
print(f"Sum of numbers from 1 to 10: {total}")

Controlling Loop Execution

Terminating a Loop with break

The break statement allows for the immediate termination of a loop, regardless of the state of the continuation condition.

for i in range(10):
    if i == 5:
        break
    print(i)

As a result, numbers from 0 to 4 will be printed.

Using break in Searches

numbers = [1, 3, 7, 9, 12, 15]
target = 9
for num in numbers:
    if num == target:
        print(f"Number {target} found")
        break

Skipping an Iteration with continue

The continue statement skips the rest of the current iteration and proceeds to the next one:

for i in range(5):
    if i == 2:
        continue
    print(i)

Result: 0, 1, 3, 4 (number 2 is skipped).

Filtering Data

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
    if num % 2 == 0:  # skip even numbers
        continue
    print(f"Odd number: {num}")

The else Block in Loops

A feature of Python is the ability to use an else block after a loop. This block is executed only if the loop completes naturally, without being terminated by a break statement.

for i in range(3):
    print(i)
else:
    print("Loop finished correctly")

Practical Application of else

def find_number(numbers, target):
    for num in numbers:
        if num == target:
            print(f"Number {target} found")
            break
    else:
        print(f"Number {target} not found in the list")

find_number([1, 2, 3, 4, 5], 3) find_number([1, 2, 3, 4, 5], 7)

 

Nested Loops

Nested loops are a construct where one loop is placed inside another. They are often used for processing multi-dimensional data structures.

Basic Example

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

Result:

i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

Creating a Multiplication Table

for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i * j:3}", end=" ")
    print()  # move to a new line

Processing 2D Lists

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for element in row:
        print(element, end=" ")
    print()

Common Errors and How to Prevent Them

Infinite Loops

One of the most common errors is creating an infinite loop:

# INCORRECT
i = 0
while i < 10:
    print(i)
    # forgot to increment i

The correct version:

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

Modifying a List During Iteration

Changing the size of a list while iterating over it can lead to unpredictable behavior:

# INCORRECT
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        numbers.remove(num)  # modifying the list during iteration

Correct approaches:

# Option 1: create a new list
numbers = [1, 2, 3, 4, 5]
odd_numbers = [num for num in numbers if num % 2 != 0]

Option 2: iterate over a copy


numbers = [1, 2, 3, 4, 5] for num in numbers[:]: # create a copy of the list if num % 2 == 0: numbers.remove(num)

 

Scope-Related Issues

Loop variables remain accessible after the loop has finished:

for i in range(5):
    pass
print(i)  # will print 4

Advanced Techniques and Patterns

The enumerate() Function

enumerate allows you to get the index of an element along with the element itself:

fruits = ["apple", "pear", "grape"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

The zip() Function

zip allows you to iterate over multiple sequences simultaneously:

names = ["Anna", "Ivan", "Maria"]
ages = [25, 30, 28]
for name, age in zip(names, ages):
    print(f"{name}: {age} years old")

List Comprehensions

A concise way to create lists using loops:

squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]

Nested Comprehensions

matrix = [[i*j for j in range(3)] for i in range(3)]
flattened = [element for row in matrix for element in row]

Optimization and Performance

Choosing the Right Loop Type

Use for to iterate over known sequences and while for loops with an indeterminate number of iterations.

Minimizing Calculations Inside Loops

# INEFFICIENT
for i in range(1000):
    result = expensive_function() + i

EFFICIENT


expensive_result = expensive_function() for i in range(1000): result = expensive_result + i

 

Using Built-in Functions

Built-in functions often work faster than explicit loops:

# Slower
total = 0
for num in numbers:
    total += num

Faster


total = sum(numbers)

 

Practical Problems and Solutions

Finding Prime Numbers

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

primes = [] for num in range(2, 50): if is_prime(num): primes.append(num) print(primes)

 

Counting Characters in a String

text = "Programming in Python"
char_count = {}
for char in text:
    if char in char_count:
        char_count[char] += 1
    else:
        char_count[char] = 1
print(char_count)

Validating User Input

def get_valid_number():
    while True:
        try:
            number = int(input("Enter a number from 1 to 100: "))
            if 1 <= number <= 100:
                return number
            else:
                print("Number must be between 1 and 100")
        except ValueError:
            print("Please enter a valid number")

valid_num = get_valid_number() print(f"You entered: {valid_num}")

 

Comparison of `for` and `while` Loops

Parameter for while
Is the range known? Yes No
Works with iterables? Yes No
Can it be replaced? In most cases Yes, but not always convenient
Primary Use Lists, strings, ranges User input, conditional loops
Code Readability High for known sequences High for conditional loops

Code Style Recommendations

Following certain style rules makes code more readable and maintainable. When working with loops, it is recommended to use meaningful variable names, avoid excessively deep nesting, and prefer built-in functions where appropriate.

Using enumerate() and zip() instead of manual index management makes the code more Pythonic. The else block in loops is a powerful but underestimated tool for creating readable search algorithms.

Conclusion

Loops in Python are a powerful tool for controlling the flow of program execution. They allow for efficient data processing, repetition of actions, and the creation of complex algorithmic constructs.

Key takeaways: the for loop is ideal for iterating over iterable objects, while is used for loops with an unknown number of iterations, and the break, continue, and else statements significantly expand loop control capabilities.

A deep understanding of loop principles is the foundation of algorithmic thinking and is critically important for any Python developer. Regular practice and experimentation with different types of loop constructs will help master this fundamental programming tool.

Frequently Asked Questions (FAQ)

How do I stop an infinite `while` loop? Add a correct exit condition or use a break statement inside the loop.

Can a `while` loop be replaced with a `for` loop? In some cases, it's possible, especially using range(), but for handling user input, while is a more suitable choice.

Does the `else` block work with a `while` loop? Yes, the else block works similarly with both for and while loops.

How do I skip the current iteration in a loop? Use the continue statement to proceed to the next iteration.

How do I exit a `for` loop prematurely? Use the break command to terminate the loop immediately.

News