Michael McKeever
Michael McKeever

Reputation: 61

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!

Upvotes: 0

Views: 10758

Answers (3)

Brett Beatty
Brett Beatty

Reputation: 5963

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

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

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

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

>>x

Output:

5

Upvotes: 3

riteshtch
riteshtch

Reputation: 8769

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
>>>

Upvotes: 5

Related Questions