我在while
/ if
条件中使用else
循环。出于某种原因,在一个条件下,while循环不起作用。条件显示在下面的代码中。在这些情况下,我会假设应该使用else
条件,weight
和max_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)
答案 0 :(得分:1)
我认为您在or
和and
之间感到困惑。
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=0
和max_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