Use a while loop when you don’t know how many times you’ll repeat — it keeps running as long as the condition is true. Here are two examples: a counter that runs 5 times, and an input() loop that keeps asking until you type q.
Example 1: counter — run 5 times #
count = 1
while count <= 5:
print("Count is:", count)
count += 1output:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
Example 2: keep asking until ‘q’ — break out #
while True:
user_input = input("Enter 'q' to quit: ")
if user_input == "q":
print("Bye!")
breakoutput:
Enter 'q' to quit: hello Enter 'q' to quit: world Enter 'q' to quit: q Bye!
