Control Flow Statements

Learn how to control the flow of your loops using continue and break statements.

Ali Berro

By Ali Berro

9 min read Section 2
From: Python Fundamentals: From Zero to Hero

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 = 0
while i < 10:
if i % 2 != 0:
i += 1
continue
print(i, end=" ")
i += 1

When 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 = 1
while 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 += 1

Which generates:

1
3
5
3
9
15
5
15
25

Another example would be for a continue statement to affect the outer loop.

i = 1
while 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 += 1

This generates:

i=1, j=1
i=1, j=2
i=1, j=3
2 is even, skip inner loop
i=3, j=1
i=3, j=2
i=3, j=3
4 is even, skip inner loop
i=5, j=1
i=5, j=2
i=5, j=3
6 is even, skip inner loop

break

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 = 0
while True:
n = int(input("Please enter a number: "))
if n < 0:
break
total += n
print("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 = True
i = 2
while i < n:
if n % i == 0:
is_prime = False
break
i += 1
if 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 = 2
while i < 10:
j = 2
while j < i:
if i % j == 0:
print(i, "is divisible by", j)
break
j += 1
i += 1

Which generates:

4 is divisible by 2
6 is divisible by 2
8 is divisible by 2
9 is divisible by 3

else

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 = 0
while i < 3:
print(i)
i += 1
else:
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 = 2
while i < n:
if n % i == 0:
print(n, "is not prime")
break
i += 1
else:
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

Checks: 0 times
Answer:
i = 1
while 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 += 1

Alternatively:

i = 1
while i <= 100:
if (i % 3 == 0 or i % 5 == 0) and not i % 15 == 0:
i += 1
continue
print(i)
i += 1

Exercise 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

Checks: 0 times
Answer:
total = 0
i = 0
while i < 10:
num = int(input())
i += 1
if num <= 0:
continue
total += num
print(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

Checks: 0 times
Answer:
total = 0
while total <= 100:
num = int(input())
total += num
print(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

Checks: 0 times
Answer:
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

Checks: 0 times
Answer:
attempts = 0
while attempts < 3:
password = input()
if password == "abcd":
print("Welcome!")
break
print("Incorrect password, try again.")
attempts += 1
else:
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

Checks: 0 times
Answer:
target = int(input())
guesses = 0
while True:
guess = int(input())
guesses += 1
if guess < target:
print("Too low")
elif guess > target:
print("Too high")
else:
print("Correct!", guesses)
break

Course Progress

Section 12 of 17

Back to Course