In this lesson, our learning goals are understand that while repeats while a condition is True, writing the basic pattern, updating loop variables correctly to avoid infinite loops, and using while for counting, summation, and simple input validation.
while means keeping doing something while the condition is True; stopping when it becomes False. It’s great when you don’t know how many repetitions you need but you know when to stop, e.g., ‘keep asking until the user inputs a number from 1 to 10’. Always update the variable involved in the condition; otherwise you’ll create an infinite loop.
Basic Pattern:
initialize variables
while condition:
body (do something)
update variables (change the condition)
Example A: Print 1 to 5
count = 1 # initialize
while count <= 5: # condition
print(count, end=" ")
count += 1 # update
print("nDone!")
Example B: Running Sum
total = 0
n = 1
while n <= 5:
total += n
n += 1
print("Sum =", total)
Example C: Limited Retries
attempts = 0
secret = 7
guess = int(input("Guess 1-10: "))
while guess != secret and attempts < 2: # 共 3 次(0,1,2)
attempts += 1
print("Wrong. Try again.")
guess = int(input("Guess 1-10: "))
if guess == secret:
print("Correct!")
else:
print("Out of tries. The answer was", secret)
Common Pitfalls:
int/float)Now we can use while to ‘keep doing something until it’s done’. Next, let’s explore for loops—when the number of repetitions is known, for is cleaner and less error-prone.