while true condition how it works
In practical terms, it will loop a code block, while
a particular condition is True
. Said condition may never be True
, in which case you get an infinite loop, or you can set and test a variable so that you have a fixed number of iterations (loops).
Any application runs in a infinite loop, until the user chooses to quit said application (crashes aside) or some other condition is becomes False
.
# This is a infinite loop
while True:
print("This will never stop")
The while statement takes an expression and a block of code.
while expression:
block
When the interpreter reaches the while
statement, it evaluates the expression. If it is true, then the interpreter runs the code inside the block, then returns to the beginning of the while
statement again.
In while True
the expression is True
, which is always true, so the loop runs forever (or until you break out of the loop using break
, or return
, or by raising an exception).
A more convincing example would be:
print("A simple vending machine\n")
coffee = 10
tea = 10
while tea > 0 or coffee > 0:
print("Remaining Tea:",tea)
print("Remaining Coffee:",coffee)
print("\nWhat would you like?\n(1) Tea\n(2) Coffee")
selection = input("> ")
if selection == '1':
if tea > 0:
print("\nHere is your Tea\n")
tea -= 1
else:
print("\nI'm sorry, but we're all out of Tea\n")
elif selection == '2':
if coffee > 0:
print("\nHere is your Coffee\n")
coffee -= 1
else:
print("\nI'm sorry, but we're all out of Coffee\n")
else:
print("Remaining Tea:",tea)
print("Remaining Coffee:",coffee)
print("Sold out")
That script will continue to run while
either tea
or coffee
is greater than zero, or True
, or until both conditions are False
: both tea
and coffee
are no longer greater than zero.
The final else
statement is not in fact necessary with this script, as there’s nothing after it, but it serves to illustrate.
Below are two examples that estimate the square root of a number using Newton’s method. Two different techniques are used to terminate the loop.
This one terminates the loop using break
:
def square_root(num, epsilon=0.0001):
# estimates square root of n
estimate = num / 2
while True:
new_estimate = (estimate + num / estimate) / 2
# if new_estimate is acceptable, break out of loop
if abs(estimate - new_estimate) <= epsilon:
break
estimate = new_estimate
return new_estimate
for i in range(1, 26):
# use the default epsilon
print(square_root(i))
This version of the function terminates the loop when return
is executed:
def square_root(num, epsilon=0.0001):
# estimates square root of n
estimate = num / 2
while True:
new_estimate = (estimate + num / estimate) / 2
# if new_estimate is acceptable, return it
if abs(estimate - new_estimate) <= epsilon:
return new_estimate
estimate = new_estimate
for i in range(1, 26):
# specify an epsilon
print(square_root(i, 0.0000001))