Fall 2024 - P3
3.8.4 While Loops
Learn to use while loops to repeat code
Basic Overview:
- A while loop is a control structure that repeatedly executes a block of code as long as a specified condition remains true.
- This type of loop is particularly useful for tasks like counting, accumulating values, or continuing until a particular condition is met.
- In this lesson, the while loop is demonstrated to display a message with a count from 1 to 3.
# In this example, we will use a while loop to display letters from 'A' to 'E' and calculate their corresponding ASCII values.
# Pseudocode:
# count ← 1
# WHILE count IS LESS THAN OR EQUAL TO 3:
# DISPLAY "This is message number" count
# count ← count + 1
# END WHILE
# Python Code:
count = 1 # Start counting from 1
while count <= 3: # Continue while count is 3 or less
print("This is message number", count) # Display the current message number
count += 1 # Increment count by 1
#Problem: Infinite Loop with a While Statement
#Write a while loop that continuously prints "Hello, World!" until you stop the program.
This is message number 1
This is message number 2
This is message number 3
What’s Happening:
- We start with the variable count set to 1.
- The loop checks if count is less than or equal to 3, and as long as this condition is true, the code inside the loop runs.
- On each iteration, the current message number is printed, and count is incremented by 1.
- Once count exceeds 3, the condition becomes false, and the loop terminates.
Additional Notes:
- Infinite Loops: Care must be taken to ensure that the condition in the loop will eventually become false; otherwise, it could result in an infinite loop that never stops.
- Practical Use Cases: While loops are great for situations where the number of iterations isn’t known ahead of time, like reading data until the end of a file or waiting for specific user input.
- Common Pitfall: A common mistake is forgetting to update the loop control variable (like count in this case), which can cause an infinite loop if the condition never becomes false.