6.6. Loops With Conditions

In the last chapter, we learned how to use conditionals to decide which block of code to run. In this chapter, we use loops to repeat a set of statements multiple times.

You might wonder:

  1. Can I put a loop inside an if statement?

  2. Can I put a conditional inside a loop?

The answer to both of these questions is a definite, YES!

6.6.1. Repeating a Check

Run the following code samples to see how each one behaves.


In this first loop, the text displayed in the console depends on whether the condition number%3 == 0 returns True. If number is evenly divisible by 3, then line 5 runs. Otherwise, line 7 runs.

In the second loop, the condition char in 'aeiou' returns True if the value of char matches any part of the string. When this happens, num_vowels gets increased by 1 (line 6). Coding ROCKS! contains 2 lowercase vowels, so line 6 only runs 2 times. For every other character in the string, the line gets skipped.

Try It!

How could you make the second program count both lowercase and uppercase vowels?

6.6.2. Looping if

We can also place a loop inside any of the code blocks of an if/elif/else statement.


if condition:
   for var_name in range(value):
      # Loop body
elif other_condition:
   for char in string:
      # Loop body
   for step in range(20):
      print("Python ROCKS!")

Set up this way, only one of the three loops will run:

  1. IF condition is True, the for loop starting on line 2 runs.

  2. IF condition is False and other_condition is True, then the loop starting on line 5 runs.

  3. IF condition and other_condition both return False, then Python ROCKS! gets printed 20 times by the last loop.

Placing a loop inside a conditional allows us to choose when the loop body should run.