Python while循环不能正常工作

时间:2016-09-06 06:50:54

标签: python if-statement while-loop

我在while / if条件中使用else循环。出于某种原因,在一个条件下,while循环不起作用。条件显示在下面的代码中。在这些情况下,我会假设应该使用else条件,weightmax_speed应该减少,直到两个while条件都无效为止。我做错了什么?

weight = 0
max_speed = 15

if weight == 0 and max_speed <= 10:
    while weight == 0 and max_speed <= 10:
        weight=weight+1
        print(weight)
        print(max_speed)
else:
    while weight != 0 and max_speed > 10:
        weight = weight-1
        max_speed=max_speed-1
        print(weight)
        print(max_speed)

2 个答案:

答案 0 :(得分:1)

我认为您在orand之间感到困惑。

and表示如果两个条件都满足,则表达式将为True。其中or表示满足任何条件。

现在基于您的代码:

weight = 0
max_speed = 15

if weight == 0 and max_speed <= 10:
    # Goes to else block since max_speed = 15 which is >10
else:
    # This while won't be executed since weight = 0
    while weight != 0 and max_speed > 10:

答案 1 :(得分:1)

假设您需要weight=0max_speed=10;你可以这样做 - &gt;

weight = 0
max_speed = 15

while weight !=0 or max_speed > 10:
    if weight>0: 
        weight = weight-1
    else:  
        weight = weight+1
    if max_speed>10:
        max_speed=max_speed-1
    print("{} {}".format(weight, max_speed))

您的输出看起来像 - &gt;

1 14
0 13
1 12
0 11
1 10
0 10
相关问题