简体   繁体   中英

While-loop with an or-condition

I want it to stop once one of the variables gets to the desired number. Why does this code wait until both variables equal 20 or greater to end?

z = 20
x = 1
y = 0
while x < z or y < z:
    inp = int(input('enter a number'))
    if x > y:
        y += inp
    elif y > x:
        x += inp
    print(x, y)

or using something like these examples just keeps adding and never stops:

while x != z or y != z:    
while x or y < z:
while x or y != z:

If the loop must stop when at least one of the variables is >= z , then you must use and to connect the conditions:

while x < z and y < z:

In your code, by using or you state that as long as one of the variables is < z , the loop must continue - and that's not what you want.

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