Flow control statements

Flow control statements#

Break and continue statements#

The break and continue statements are used in loops (while or for) to modify the behaviour of the loop. break ends the loop, while continue ends the current iteration and continues onto the next one.

Example use of break statement:

counter = 0
while True:  # Create an infinite loop
    counter += 1
    
    if counter > 29:
        break  # Exit the loop if counter is 30 or more
        
print(counter)
30

Example use of continue statement:

for i in range(10):
    if i%2 == 1:  # Skip odd values
        continue
        
    print(i)
0
2
4
6
8

Pass statement#

pass statement is used in the code to “do nothing”.

for i in range(10):
    
    if i%2 == 1: # Do nothing for odd numbers
        pass
    else: # Multiply even numbers by 4
        i *= 4
        
    print(i)
0
1
8
3
16
5
24
7
32
9

Exercises#


  • Floods You are in charge of providing a software which will detect possible floods. You are given a time series of water levels (a list of integers) and a critical level (also an int). If water level rises, you should print 1 and if it falls print -1. If the level stays the same, the programme should do nothing. As soon as the detection is above the critical level, terminate the programme.

water_level = [0,1,1,2,3,4,5,3,2,4,7,8]