Fall 2024 - P3
3.8.2 Use While loops to print strings with booleans
Learn to use while loops to repeat code
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.
1
2
3
4
5
5
4
3
2
1
What’s Happening:
- A while loop is a control structure that allows us to execute a block of code repeatedly as long as a specified condition is true.
- In this example, we start with a variable count set to 1 and continue looping until count exceeds 3.
- Each time the loop executes, it displays a message that includes the current value of count and then increments count by 1.
- This method can be useful for tasks like counting, accumulating values, or running a block of code until a certain condition changes.
- If the condition never changes (e.g., if the loop’s terminating condition is never met), it can lead to an infinite loop, which continuously runs the code without stopping.
Additional Notes:
- Infinite Loop: It’s important to ensure that the condition in the while loop will eventually become false; otherwise, you may create an infinite loop that never stops running.
- Control Flow: While loops can help manage the flow of your program, especially in cases where you do not know in advance how many times you need to repeat a task.
- Common Use Cases: While loops are often used in scenarios like reading data until the end of a file, processing user input until a specific command is given, or performing actions until a desired outcome is achieved.