Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The for loop
The while loop
Nested loops
15. Nested while loops
break and continue
Summary

Instruction

Great! In the previous examples, we showed nested for loops. Naturally, while loops can be nested too!

final_score = 0
counter = 0

while counter < 10:
  current_number = input('Please provide a number to add: ')
  while not current_number.isnumeric():
    current_number = input('That\'s not a number! Try again: ')
  final_score += int(current_number)
  counter += 1

print('The score is', final_score)

The program above adds 10 numbers entered by the user. We use nested while loops. The outer loop is responsible for reading in 10 numbers.

The inner loop, in turn, makes sure that the user enters a number, and not letters or special characters. It keeps asking for input until it's numerical. When we get a legit number at last, we add it to the final_score in the outer loop.

Exercise

Use nested while loops to create a program that prints the mean of the provided numbers. First, the program should ask how many numbers will be provided. Then, the program should repeatedly ask the user for a number (Provide a number: ). If user types anything else, the program should continuously ask to provide a number (Wrong! That's not a number! Try again: ).

Stuck? Here's a hint!

You will need to create two variables before starting a loop: one for summing all the numbers, and one to act as a counter. Use the counter variable in the outer loop and increase it by 1 when the user provides a number.