while
Loops
An infinite loop occurs when the loop keeps executing and does not stop. Why does this happen?
The following while
loops are guaranteed to be infinite:
total = 0.0
answer = input("Buy a ticket?")
while answer == "Y":
p = process_ticket()
total = total + p
print(f"Total price is $[total:.2f}")
This loop is infinite because the loop condition variable, answer
,
is never changed in the body of the loop. If a loop condition variable is
never changed then it cannot cause the loop condition to be falsified.
print("Let's play 20 Questions!")
n = 20
while n > 0:
ask_question()
n = n + 1
This loop is infinite because the loop condition variable, n
,
is changed in the wrong direction. It never reaches 0, which requires
subtraction, not addition.
n = int(input("Input a grade from 0 to 100 (-1 to stop): "))
while n >= 0 or n <= 100:
process_mark(n)
n = int(input("Input a grade from 0 to 100 (-1 to stop): "))
This loop is infinite because the loop condition is incorrect. The
conditions have an or
between them. Thus, so long as one of
the conditions is True
, the loop continues to execute. Assume
n
is -1. The condition n >= 0
evaluates to False
,
but the condition n <= 100
evaluates to True
,
and the loop continues. This condition should use an and
instead of an or
.
while True:
...
This is infinite for obvious reasons. Don't use this type of loop in CP104.
Note: The Executing a Python Program of the Using Eclipse with PyDev explains how to identify and kill an infinite loop in Eclipse.
while
Loop Checklist
while
loop is correct when:
True
,
the loop executes at least once. Otherwise the loop does not execute at
all.