Control Flow Statements
Sometimes when we are working inside a loop, we don’t want to continue the remainder of the current iteration. It would be helpful if we had a way to skip the rest of the iteration and go to the next one. Other times we would want a way to completely terminate the current loop. Luckily many programming languages, including Python supports this control flow option, using the keywords continue and break.
continue
continue skips the remainder of the current enclosed loop and goes to the condition to start a new iteration.
i = 0while i < 10: if i % 2 != 0: i += 1 continue print(i, end=" ") i += 1When running this code, for each odd number, if we reach an odd number, we will stop the current iteration and go to the next one. Thus the output will be 0 2 4 6 8.
If we didnt change the value of i in the if statement, then we would have reached an infinite loop (an unintended one).
In the case where we have multiple loops, or nesting of loops, the inner most loop which has the continue statement will be the effected one.
i = 1while i < 7: j = 1 while j < 7: product = i * j if product % 2 == 0: # <-- Skip all the multiples of 2 j += 1 continue print(product) j += 1 i += 1Which generates:
135391551525Another example would be for a continue statement to affect the outer loop.
i = 1while i <= 6: if i % 2 == 0: print(f"{i} is even, skip inner loop") i += 1 continue j = 1 while j <= 3: print(f"i={i}, j={j}") j += 1 i += 1This generates:
i=1, j=1i=1, j=2i=1, j=32 is even, skip inner loopi=3, j=1i=3, j=2i=3, j=34 is even, skip inner loopi=5, j=1i=5, j=2i=5, j=36 is even, skip inner loopbreak
break is similar to continue, but instead of skipping the remainder of the current iteration, it terminates the current loop and goes to the next statement after the loop. It is used to finish early from a loop.
total = 0while True: n = int(input("Please enter a number: ")) if n < 0: break total += nprint("The sum of all positive numbers is:", total)Another example would be to check if a number is prime.
n = int(input("Please enter a number: "))is_prime = Truei = 2while i < n: if n % i == 0: is_prime = False break i += 1if is_prime: print(n, "is prime")else: print(n, "is not prime")We have written a code snippet similar to this, but this is neater and more readable. The break statement breaks out of the inner most loop, and goes to the next statement after the loop.
i = 2while i < 10: j = 2 while j < i: if i % j == 0: print(i, "is divisible by", j) break j += 1 i += 1Which generates:
4 is divisible by 26 is divisible by 28 is divisible by 29 is divisible by 3else
The else statement is used to execute a block of code after a loop finishes normally, i.e. without a break statement. When the while loop condition becomes False, the else statement is executed.
i = 0while i < 3: print(i) i += 1else: print("Loop finished")This will print 0 1 2 Loop finished. This doesn’t look anything we know off, but it actually exists in Python. It makes some code snippets more readable and easier to comprehend. Going back to our previous example, we can use the else statement to print a message when the loop finishes normally.
n = int(input("Please enter a number: "))i = 2while i < n: if n % i == 0: print(n, "is not prime") break i += 1else: print(n, "is prime")Exercises
Below are exercises to practice control flow statements (continue, break, and else). Try solving them on your own before checking the solutions.
Exercise 1: Skip numbers divisible by 3 or 5 (but not both)
Write a program which prints all the numbers from 1 to 100, but it skips the numbers which are divisible by 3 or 5, but not both.
Example: The number 3 is divisible by 3 but not by 5, so it should be skipped. The number 15 is divisible by both 3 and 5, so it should NOT be skipped.
Skip Numbers Divisible by 3 or 5
i = 1while i <= 100: divisible_by_3 = i % 3 == 0 divisible_by_5 = i % 5 == 0 if (divisible_by_3 or divisible_by_5) and not (divisible_by_3 and divisible_by_5): i += 1 continue print(i) i += 1Alternatively:
i = 1while i <= 100: if (i % 3 == 0 or i % 5 == 0) and not i % 15 == 0: i += 1 continue print(i) i += 1Exercise 2: Sum positive numbers from 10 inputs
Write a program which asks the user to enter 10 numbers, and sums only the positive numbers. The program should print the sum of the positive numbers.
Sum Positive Numbers
total = 0i = 0while i < 10: num = int(input()) i += 1 if num <= 0: continue total += numprint(total)Exercise 3: Sum until exceeding 100
Write a program which asks the user to enter numbers, until the sum exceeds 100. The program should print the sum of the numbers entered.
Sum Until Exceeds 100
total = 0while total <= 100: num = int(input()) total += numprint(total)Exercise 4: Password check (unlimited attempts)
Write a program which asks the user to enter a password, and keeps asking until the user enters the correct password. The correct password is “abcd”. For each incorrect password, the program should print “Incorrect password, try again.”. Once the user enters the correct password, the program should print “Welcome!”.
Password Check
while True: password = input() if password == "abcd": print("Welcome!") break print("Incorrect password, try again.")Exercise 5: Password check with 3 attempts (using else)
Write a program which asks the user to enter a password, with only three attempts. For each incorrect password, the program should print “Incorrect password, try again.”. Once the user enters the correct password, the program should print “Welcome!”. If the user enters the incorrect password three times, the program should print “Too many incorrect attempts, please try again later.” using the else statement.
Password Check with 3 Attempts
attempts = 0while attempts < 3: password = input() if password == "abcd": print("Welcome!") break print("Incorrect password, try again.") attempts += 1else: print("Too many incorrect attempts, please try again later.")Exercise 6: Number guessing game
Write a program which asks the first user to enter a number, and then asks the second user to guess the number. The second user should keep guessing until they guess the number correctly. Each time the second user guesses, the program should print “Too high” if the guess is too high, “Too low” if the guess is too low, and “Correct!” if the guess is correct along with the number of guesses the second user has made.
Number Guessing Game
target = int(input())guesses = 0while True: guess = int(input()) guesses += 1 if guess < target: print("Too low") elif guess > target: print("Too high") else: print("Correct!", guesses) break