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. Now you might wonder how you can combine loops and conditionals.
Repeating a Check
Check out 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.
Looping with If
We can also place a loop inside any of the code blocks of an if/elif/else
statement.
|
|
Set up this way, only one of the three loops will run:
- IF
condition
isTrue
, thefor
loop starting on line 2 runs. - IF
condition
isFalse
andother_condition
isTrue
, then the loop starting on line 5 runs. - IF
condition
andother_condition
both returnFalse
, thenPython 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.