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:
Can I put a loop inside an if statement?
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
number%3 == 0 returns
number is evenly
divisible by 3, then line 5 runs. Otherwise, line 7 runs.
In the second loop, the condition
char in 'aeiou' returns
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.
How could you make the second program count both lowercase and uppercase vowels?
We can also place a loop inside any of the code blocks of an
1 2 3 4 5 6 7 8 9
if condition: for var_name in range(value): # Loop body elif other_condition: for char in string: # Loop body else: for step in range(20): print("Python ROCKS!")
Set up this way, only one of the three loops will run:
forloop starting on line 2 runs.
True, then the loop starting on line 5 runs.
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.