Skip to the content.

3.8.2 Use While loops to print strings with booleans

Learn to use while loops to repeat code

CSP Big Ideas

Basic Overview

  • A while loop is a programming structure that allows us to execute a block of code repeatedly as long as a condition is true.
  • This can be particularly useful for counting or accumulating values.
  • In this example, we will use a while loop to display messages a specific number of times.
# count ← 1
# increasing ← TRUE
#
# WHILE increasing IS TRUE:
#     DISPLAY count
#     count ← count + 1
#     IF count IS GREATER THAN 5:
#         increasing ← FALSE
# END WHILE
#
# WHILE increasing IS FALSE:
#     count ← count - 1
#     DISPLAY count
#     IF count IS EQUAL TO 1:
#         increasing ← TRUE
# END WHILE


i = 1  # Start counting from 1
increasing = True  # Initialize the boolean flag

# Count up from 1 to 5
while increasing:
    print(i)
    i += 1
    if i > 5:
        increasing = False  # Stop increasing once 5 is reached

# Count down from 5 to 1
while not increasing:
    i -= 1
    print(i)
    if i == 1:
        increasing = True  # Reset once 1 is reached

#Problem:
#Use a boolean value to indefinitely print a string, or a message of your personal choice.