exiting a while loop
Peter Otten
__peter__ at web.de
Fri May 22 07:58:06 EDT 2020
John Yeadon via Python-list wrote:
> Am I unreasonable in expecting this code to exit when required?
It is unreasonable to expect something that doesn't match what you read in
the tutorial ;)
If you want to terminate the script you can use exit. However exit is a
function, and you have to call it
exit()
to actually do anything.
If you want to terminate just the loop, which is more likely because there
is a print() following it, you can do this with break (which is a statement,
so no trailing ()):
> # Add up the powers of 2 starting with 2**0 until 2 million is met.
> n = 1
> target = 2000000
> sum = 0
>
> while True:
> x = 2 ** (n - 1)
> sum += x
> print(n, sum)
> if sum >= target:
> print("Target met.")
break
> n += 1
>
> print("\n", n, "terms are required.")
More information about the Python-list
mailing list