osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

exiting a while loop


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