exiting a while loop
Dan Sommers
2QdxY4RzWzUUiLuE at potatochowder.com
Fri May 22 07:57:36 EDT 2020
On Friday, May 22, 2020, at 7:49, John Yeadon via Python-list wrote:
> Am I unreasonable in expecting this code to exit when required?
Yes. :-)
> # 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.")
> exit
Try break instead of exit. See
https://docs.python.org/3/reference/compound_stmts.html#the-for-statement
for more information.
> n += 1
>
> print("\n", n, "terms are required.")
--
“Atoms are not things.” – Werner Heisenberg
Dan Sommers, http://www.tombstonezero.net/dan
More information about the Python-list
mailing list