Combining loops and logic
All of our examples so far have been relatively simple individual logical statements, but there is no reason that we cannot apply logical operations in loops.
For example, we can modify our earlier example of checking whether numbers are odd or even to use an if statement inside of a for loop
for value in range(10):
if value % 2 == 1:
print(f'{value:d} is odd')
else:
print(f'{value:d} is even')Say we now wanted to stop the program after the third even number is found. We can do this by adding a counter variable and a break statement inside of our if block.
even_count = 0
for value in range(10):
if value % 2 == 1:
print(f'{value:d} is odd')
else:
even_count += 1
print(f'{value:d} is even')
if even_count == 3:
breakThis program will now stop executing once the third even number is found.
Alternatively, we could use the continue statement to skip odd numbers entirely.
for value in range(10):
if value % 2 == 1:
continue
else:
print(f'{value:d} is even')continue tells Python to skip the rest of the current loop iteration and move on to the next one, so in this case, odd numbers are ignored entirely.
In fact, we can make this code even simpler by removing the else block entirely, since if the if condition is met, the continue will skip to the next iteration anyway.
for value in range(10):
if value % 2 == 1:
continue
print(f'{value:d} is even')So the two keywords continue and break can be used inside of loops to modify their behaviour based on logical conditions.