简体   繁体   中英

Python - Stay in loop Until condition is met

I am wanting to write a loop that stays in the loop until a condition is met.

Here's the code so far, and I'm not sure if all is correct, I have little experience in while loops:

x = 2885
y = 1440
difference = 0
while True:
     if x > y:
          difference = x - y
          break

So what I want is to keep subtracting my constant y from x until

y > x

and to have the final

difference = 5

Any help is much appreciated, thanks in advance!

Wouldn't a better way be to just use modulus.

>>> x = 2885
>>> y = 1440
>>> x%y
5
>>> 

Or still using loops

>>> x = 2885
>>> y = 1440
>>> while x >= y :
...     x = x - y
... 
>>> x
5
>>>

Instead of True as the condition for execution, just put x > y :

x = 2885
y = 1440
while x >= y:
   x -= y

>>x

Output:

5

Modulus is your best solution, but this is also possible in a fairly simple for loop if you insist on a looping solution.

>>> x = 2885
>>> y = 1440
>>> for i in range(x, -1, -y): # -1 as substitution for inclusive 0
...     pass
...
>>> i
5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM