简体   繁体   English

Python-保持循环直到满足条件

[英]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: 这是到目前为止的代码,我不确定是否正确,我对while循环的经验很少:

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 所以我要继续从x减去常数y直到

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 : 除了将True作为执行条件之外,只需输入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. 模数是您最好的解决方案,但是如果您坚持使用循环解决方案,那么在相当简单的for循环中也可以实现。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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