The while Loop

The 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 False. The 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:

[ ]:

Game Programming

At the heart of very operating system and graphical program there is a while loop. A while loop is the heart of any game. Here’s an example of a game that uses a while loop:

[ ]:
import random

def dice_game():
    while True:
        command = input('Type "roll" to roll the dice or "quit" to exit: ')
        if command == 'roll':
            die1 = random.randint(1, 6)
            die2 = random.randint(1, 6)
            if die1 == 1 and die2 == 1 :
                print ("The dice say snake eyes!")
            else:
                print (f"The dice say {die1} and {die2}")
        elif command == 'quit' :
            return

dice_game()