THEORY AND PRACTICE

  • Input and Output Data
    • Tasks
  • Conditions
    • Tasks
  • For Loop
    • Tasks
  • Strings
    • Tasks
  • While Loop
    • Tasks
  • Lists
    • Tasks
  • Two-Dimensional Arrays
    • Tasks
  • Dictionaries
    • Tasks
  • Sets
    • Tasks
  • Functions and Recursion
    • Tasks

Lesson 3. The for loop in python

Python for loop for iteration

Python for loop: definition

The for loop is one of the fundamental control constructs in Python. It is designed for iteration (or sequential iteration) of elements in any iterable object, such as lists, strings, dictionaries, or ranges of numbers. Simply put, the for loop takes a collection of elements and executes a block of code for each of these elements in turn.

Purpose and applications

The main purpose of the for cycle is to automate repetitive tasks. Instead of writing the same code many times for different elements, you write it once inside a loop, and Python applies it to the entire collection.

The fields of application are limitless:

  • Processing of each file in the folder.
  • Reading each line from a text file.
  • Performing mathematical operations on each number in the list.
  • Checking each user in the database for compliance with any condition.

General structure of the for loop

For and in loops in Python

The syntax of the for loop is simple and intuitive. He always uses the keywords for and in.

for temporary variable in iterable object:
    # A block of code that will be executed for each element
                        
  • for: The keyword that starts the cycle.
  • temporary variable: A name that you come up with. In each iteration (repetition) of the loop, this variable will be assigned another element from the iteration_object. For example, if we iterate through the list>[10, 20, 30], this variable will first be 10, then 20, and then 30.
  • in: A keyword that binds a temporary variable to a collection.
  • iterable_object: A collection of items to iterate through (for example, a list, a string).
  • :: A colon is required at the end of the line, it tells Python that the next block of code will be related to the loop.

A block of code in a loop

All code that must be executed inside the loop must be indented (usually 4 spaces). It is the indentation that shows Python which commands belong to the loop and which do not. As soon as the indentation ends, the cycle is considered completed.

Iterating over different collections

The forloop is universal and can work with different types of data collections in Python.

Iterating through lists

Lists are one of the most common objects to search through. The for loop will run sequentially through each element of the list from the beginning to the end.

Example with a list of numbers

Suppose we have a list of grades, and we want to print each of them.

grades = [5, 4, 5, 3, 4, 5]
print("Student's grades:")
for grade in grades:
    # The 'grade' variable will take a new value from the list at each iteration.
    print(grade)
print("The evaluation is completed.")
                        

Line—by-line iteration

A string in Python is also an iterable object. It is considered as a sequence of characters.

Character search features

When iterating over a string, the temporary variable will take on the value of each character in turn, including spaces and punctuation marks.

message = "Hello, world!"
for char in message:
    # The variable 'char' (from character) will contain one character per iteration
    print(char)
                        

Dictionary iteration

Dictionaries store data in the form of "key" pairs:the value of". By default, the dictionary is iterated using its keys.

user_info = {
"name": "Alexey",
"age": 30,
"city": "Moscow"
}

print("Key search (default behavior):")
for key in user_info:
    # 'key' will take the values "name", "age", "city"
    print(key) 
                        

Iterating over dictionary values

If you only need values, use the .values() method.

print("\parse by values:")
for value in user_info.values():
# 'value' will take the values "Alexey", 30, "Moscow"
    print(value)
                        

Iteration by keys and key-value pairs (optional)

To get both the key and the value at the same time, use the .items() method. This is the most convenient way to iterate through dictionaries.

print("\Parsing by key-value pairs:")
for key, value in user_info.items():
    # We immediately get both the key and the value in two different variables.
    print(f"Key: {key}, Value: {value}")
                        

range() function: generating numeric sequences

Function assignment and description

It is often necessary to run a loop a certain number of times without being tied to a specific collection. There is a built-in range() function for this. It creates a special object that generates a sequence of integers on the fly without storing them all in memory.

Parameters of the range function(start, stop, step)

The range() function can take from one to three arguments:

  • range(stop): Generates numbers from 0 to stop - 1.
  • range(start, stop): Generates numbers from start to stop - 1.
  • range(start, stop, step): Generates numbers from start to stop - 1 in increments of step.

Important: The upper bound (stop) is never included in the sequence!

Iterating over numeric sequences with range()

The combination of for and range() is a classic way to organize a loop with a set number of repetitions.

Example of a simple iteration by range()

Let's run the code block 5 times.

# range(5) generates the sequence 0, 1, 2, 3, 4
for i in range(5):
    print(f"Repeat number {i}")
                        

Increment and decrement

The concept of increment and decrement

Increment — increasing the value

An increment is an operation to increase a numeric variable by a certain amount (most often by 1).

Decrement — decrease in value

Decrement is the reverse operation, reducing a numeric variable.

Variable increment in Python

Absence of the ++ operator

Unlike languages like C++ or Java, Python does not have increment operators ++ and decrement --. Trying to use them will cause a syntax error.

Using the += operator

The addition operator with the assignment += is used for the increment. The entry \[ x += 1 \] is a short form for \[ x = x + 1 \].

Example of increasing a variable by 1

Let's calculate how much money we will accumulate by saving 1 coin 10 times.

wallet = 0 # Initial number of coins
for i in range(10):
# Increase the value of the wallet variable by 1
    wallet += 1
    print(f"Day {i+1}: coins in {wallet} wallet")
                        

Variable decrement in Python

Using the -= operator

The subtraction operator with assignment -= is used for the decrement. The entry \[ x -= 1 \] is a short form for \[ x = x - 1 \].

Example of reducing a variable by 1

Countdown before rocket launch.

timer = 10
print("Starting the countdown!")
while timer > 0:
    print(timer)
    # Reduce the timer by 1
    timer -= 1
print("Start!")
                        

Using increment and decrement with other operators

*Mathematical operators if

The += and -= operators are part of the family of "assignment operators with an operation". There are also *=, /=, %= and others. They can be used inside conditional constructions (if).

Application examples with different operators

Let's calculate the sum of only even numbers from 1 to 10.

total_sum = 0
for number in range(1, 11): # Numbers from 1 to 10
    # Check if the number is even
    if number % 2 == 0:
        print(f"Found an even number: {number}. Add to the amount.")
        # Increment the amount only if the condition is met
        total_sum += number

print(f"The total sum of even numbers: {total_sum}") # 2 + 4 + 6 + 8 + 10 = 30
                        

Using variables instead of numbers for increment

The amount by which you increase or decrease a variable does not have to be a constant. It may be a different variable.

account = 100
deposits = [10, 50, 25, 15] # List of deposits

for deposit_amount in deposits:
    # Increasing the invoice by the amount from the list
    # \[ account += deposit_amount \]
    account += deposit_amount
    print(f"The account has been credited to {deposit_amount}. Current balance: {account}")
                        

Iteration with the initial value and step

Explanation of the start, stop, step parameters in range()

We can fully control the sequence generated by range() using all three parameters.:

  • start: The first number in the sequence.
  • stop: The boundary up to which the generation proceeds (not including the boundary itself).
  • step: The step with which the number changes on each iteration.

Example of iteration in increments of +2

Let's print all the even numbers from 2 to 10 inclusive.

#We start with 2, go up to 11 (so that 10 is included), in steps of 2
for number in range(2, 11, 2):
    print(number)
                        

Features of using a negative step (decrement) — optional

If the step (step) is negative, the cycle will go in reverse order. In this case, the start value must be greater than the stop value.

print("Countdown in steps of -3:")
# Start at 10, go to 0 (not including), in steps of -3
# Sequence: 10, 7, 4, 1
for i in range(10, 0, -3):
    print(i)
                        

Cycle control for

Sometimes we need to change the standard behavior of a loop: abort it prematurely or skip the current iteration.

The break operator in Python loops for

Appointment — early exit from the cycle

The break statement immediately and completely stops the loop execution. The code jumps to the first line after the loop block.

Example of using break

We are looking for the first number in the list, which is divisible by 7. As soon as we find it, we stop the search.

numbers = [12, 45, 23, 49, 16, 56, 8]
found_number = None

for num in numbers:
    print(f"Checking the number {num}...")
    if num % 7 == 0:
        found_number = num
        print(f"Found a number that is divisible by 7: {num}. Breaking the cycle.")
        break # Getting out of the loop

if found_number:
    print(f"First number found: {found_number}")
                        

Python continue operator loop control

Skipping the rest of the code in the current iteration

Moving on to the next iteration

The continue operator only interrupts the current iteration. It skips all the remaining code inside the loop block for the current element and immediately moves on to the next element in the sequence.

Example of using continue

Let's process the list, but ignore all negative numbers.

data = [10, -5, 20, 0, -15, 30]
processed_data = []

for item in data:
    if item < 0:
        print(f"Encountered a negative number {item}. Skip it.")
        continue # We proceed to the next element without executing the code below
    
    print(f"Processing the number {item}.")
    processed_data.append(item)

print(f"Processed data (positive only): {processed_data}")
                        

The else block in the for loop

When the else block is executed

In Python, the for (and while) loops have a unique feature — the else block. The code in this block is executed only if the loop ended naturally, that is, it went through all the iterations and was not interrupted by the break operator.

Example of a loop with else without interruptions break

We check if there is "milk" in the shopping list. In this example, it is not present, the cycle will end before the end.

shopping_list = ["bread", "eggs", "cheese"]
for item in shopping_list:
    print(f"Checking: {item}")
    if item == "milk":
        print("Milk found!")
        break
else:
    # This block will be executed because break was not called
    print("The cycle ended, but the milk was not found in the list.")
                        

Else behavior when using break is not performed

Now let's add "milk" to the list. The loop will be interrupted, and the else block will fail.

shopping_list = ["bread", "milk", "eggs", "cheese"]
for item in shopping_list:
    print(f"Checking: {item}")
    if item == "milk":
        print("Milk found!")
        break # Interrupting the loop
else:
    # This block will NOT be executed
    print("The cycle ended, but the milk was not found in the list.")
                        

Additional notes and tips

Nested for—mention loops (optional)

You can put one loop inside another. This is called a nested loop. The outer loop performs one iteration, while the inner loop manages to complete its work during this time. This is useful for working with two-dimensional structures, such as matrices or for creating tables.

# Example of a multiplication table
for i in range(1, 4): # Outer loop(rows)
    for j in range(1, 4): # Inner loop(columns)
        print(f"{i} * {j} = {i*j}", end="\t") # end="\t" for single line tab output
    print() # Jumps to a new line after the end of the inner loop
                        

Using for loops with functions and generators (optional)

for loops work great with functions that return iterable objects. A special type of function, generators (using yield), create values one at a time, which is ideal for processing large amounts of data in a for loop without spending memory.

Practical tips for effective use of cycles

  1. Give meaningful names to variables. Instead of for i in list1: write for user in users: or for product in products:. The code becomes much more readable.
  2. Do not change the collection you are iterating on. Adding or removing items from the list during its iteration can lead to unpredictable behavior and errors. It's better to create a new list for the results.
  3. Keep the body of the loop short. If the code block inside the loop becomes too large and complex, put its logic in a separate function. This will improve readability and allow code reuse.