Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

While Loops

In Python, event-controlled loops are written using a while statement and are called while loop. A while statement tests for an initial condition, and the lines of code indented under while run only when the initial condition is True.

In each iteration through the while loop, Python will:

  • Evaluate the initial condition (which is a Boolean true/false expression)

  • If the condition is False, exit the loop and continue the program

  • If the condition is True, then execute other statements in the body of the loop and return to the beginning of the loop

A while statement tests for an initial condition, and the lines of code indented under while run only when the initial condition is True.

The basic syntax for a while loop:

# while loop sample syntax
while condition:
	statement(s)

To express this logic another way:

# while loop sample syntax
while THIS CONDITION IS TRUE:
	DO THIS THING

Python Example

A guessing game is a classic while loop scenario.

# correct answer
secret = 7

# guess
guess = int(input("Guess a number: "))

# while statement
while guess != secret:
  if guess > secret: # initial condition
    print("Your guess is too high. Better luck next time")
    guess = int(input("Guess again. Enter another number: "))
  else: # else statement
    print("Your guess is too low. Better luck next time.")
    guess = int(input("Guess again. Enter another number: "))


print("Congrats, you guessed the secret number!") # final message

Because the number of times the loop will execute is not known, this is an example of an event-controlled loop. That is, the loop will continue executing (looping) until the initial condition (guess != secret) is no longer true.

Application

Q3: Return to your Q1 color guessing game program. Rewrite the program to use a whlie statement and continue until the user guesses your favorite color. This program will use a combination of the input() function, comparison operators, a while statement, and if-then-else logic. Answer to this question includes program + comments that document process and explain your code.

Q4: Given the following program:

# assign count variable
count = 1

# while loop
while count <= 5: # initial condition
   print ("Python") # print statement
   count = count + 1 # reassign count

# final print statement
print ("Done")

How would you modify the program to print or output the string nine (9) times and also include line numbers as part of the output? Answer to this question includes program + comments that document process and explain your code.

For example, your output might look like the following:

1 Python
2 Python
3 Python
4 Python
5 Python
6 Python
7 Python
8 Python
9 Python
IS FUN!