while loop is known as the indefinite loop. You use it when you can’t know how many times you need to go through the loop. The
while loop continues looping while the loop condidtion is
True and exits the loop when the condition is
while loop is less common than the
for loop but still essential for most programs.
Let’s revisit our guessing game. In this version of the game we want the user to keep guessing until they get the right answer. There’s no way to know how many guesses it will take them.
guess = 0 while guess != 34: guess = int(input("Pick a number between 1 and 100: ")) print("You got it!")
Try entering the code into the next cell:
The loop in the previous cell asks for input until the user provides the correct value. This is a useful behavior when you want to validate the input a user gives you. Here’s an example, here’s a program that asks for a number between 1 and 100 and forces the user to type in something correct.
def input_number(): number = -1 while not 1 <= number <= 100: number = int(input("Enter an integer between 1 and 100: ")) return number n = input_number() print("Thank you for typing:", n)
Enter an integer between 1 and 100: 23
Thank you for typing: 23
while loops are a bit more hazardous than
for loops because a programming mistake can make them infinite loops. Getting stuck in an infinite loop is one of the ways a program can crash and become unresponsive. So more care is needed when you program a
while loop. Somtimes
while loops are written as infinite loops with a
return statement that terminates the loop. Here’s the input validation function again:
def input_number(): while True: number = int(input("Enter an integer between 1 and 100: ")) if 1 <= number <= 100: return number n = input_number() print("Thank you for typing:", n)
Enter an integer between 1 and 100: 32
Thank you for typing: 32
Does the difference between the two ``input_number`` functions seem like a big deal? Probably not. Here’s a practice problem. Try writing it both ways:
Write a function called
number_between that takes two arguments, a
minimum and a
maximum number. The function asks the user for input with the
input function and returns a number between
maximum. If the user types an invalid number the function keeps asking for a valid one.
minimum: (int) The minimum number (inclusive)
maximum: (int) The maximum number (inclusive)
Returns: (int) an integer between