Editor settings

General settings

Save settings

Learn to program with Python

Combine for loops with if statements #

for loops and if statements can be combined to perform more complex operations. A common use case is to loop through a list and perform a specific action based on a condition.

Here's an example of how to use a for loop with an if statement. Note the level of indentation for each code block:

for number in range(10):
    if number > 5:
        print(number)
Output:
6
7
8
9

In the example above, we loop through numbers from 0 to 9. However, with each iteration, we check that the variable number is greater than 5 to call the print() function, which we can see from the output showing the numbers only from 6 to 9.


Exercise #

  • Add an if statement within the for loop so that my_numbers only contains the numbers from 0 to 10.
Output will be displayed here