4.3. Loop control#

Sometimes it may be necessary to interrupt the normal flow of a loop to either terminate the the loop before the loop has been completed or to move to the next iteration straight away. To do this Python uses the break and continue commands.


4.3.1. Break#

The break command is used to exit a loop straight away without executing any more commands within the loop. To demonstrate the use of a break command enter the following code into your program.

# The break command
print()
for i in range(5):
    if i == 3:
        break
    
    print(i)

Run your program and you should see the following printed to the console

0
1
2

Here the if statement inside the for loop terminates the loop then i is equal to 3.


4.3.2. Continue#

The continue command moves onto the next cycle of a loop straight away without executing any following commands in the loop. To demonstrate the use of a continue command enter the following code into your program.

# The continue command
print()
for i in range(5):
    if i == 3:
        continue
    
    print(i)

Run your program and you should see the following printed to the console

0
1
2
4

Here the if statement inside the for loop skips the iteration when i is equal to 3 and continues to the next iteration.


4.3.3. Exercises#

Exercise 4.6

A prime number is a positive integer greater than 1 which is only divisible by 1 and itself. Write a program that uses a for loop to determine whether an integer is prime or not. Use your program to determine of the following are prime:

  1. 1009 (prime)

  2. 2123 (not prime)

  3. 6269 (prime)

  4. 8441 (not prime)

Hint: The command n % i returns 0 if n is divisible by i.

Exercise 4.7

Use a while loop to create a guessing game where the user has to guess the value of a random integer between 0 and 100. For each guess the game will tell the user whether their guess is greater or less than the random integer. The user wins the game if they guess correctly within 5 guesses.

Hints:

  • the command int(input("text")) can be used to prompt the user to enter an integer

  • the NumPy command np.random.randint(a, b) generates a random integer in the range a to b