In my previous article we were talking about the for loop. Today we’ll be talking about the basics of while loops.
Here’s the video version of this article:
The while loop is used if we don’t know how many times the code should be repeated, but usually the loop runs as long as there’s a condition that is met. So, this is a condition-controlled loop.
Right after the while keyword we write the condition. It will be checked on each loop run. As long as it’s met, the loop will run. As soon as the condition is no longer met, the loop stops. After the condition we use a colon, and in the next line we start writing the code that will be repeated – the body of the loop. Naturally, this block of code is indented appropriately. The variables that we’re using have to be initialized before.
Here’s an example:
number_to_guess = 7
your_guess = 0
guesses = 0
while your_guess != number_to_guess:
your_guess = int(input("Enter a number between 1 and 10: "))
if your_guess != number_to_guess:
print("Wrong. Try again.")
guesses += 1
print("You needed {} guess(es) to win.".format(guesses))
And here’s a possible output:
Enter a number between 1 and 10: 3
Wrong. Try again.
Enter a number between 1 and 10: 9
Wrong. Try again.
Enter a number between 1 and 10: 1
Wrong. Try again.
Enter a number between 1 and 10: 7
You needed 4 guess(es) to win.
So, how does the code work? Your task is to guess a number between 1 and 10. The code in the loop asks you to enter a number from this range and it continues as long as you enter a wrong number. If you enter a wrong number, you are informed that you were wrong and the value of the variable guesses, which holds the number of how many times you were trying to guess, is incremented by one.
After you finally guess the number, which is 7, the condition your_guess != number_to_guess isn’t met anymore and the loop stops. Finally you get a message which tells you how many guesses you needed to win. This message comes from the print function which is outside the loop.