Python while循环无法正常工作

问题描述:

我在if/else条件中使用while循环。出于某种原因,在一种情况下while循环不起作用。条件显示在我的代码下面。在这些条件下,我会假定应该使用else条件,并且应该减少weightmax_speed,直到while条件不再有效。我究竟做错了什么?Python 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

用的是什么,而在这里循环?我不能理解它背后的逻辑。你想实现什么目标? –

+5

它进入'else'分支,但由于weight为'0',因此'weight!= 0'的计算结果为'False',因此整个'weight!= 0和max_speed> 10'表达式的计算结果为'False'。这就是为什么while循环不能运行的原因。 – Sevanteri

+0

你想要'weight = 0'和'max_speed = 10'吗? – jbsu32

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

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

你的输出看起来像 - >

1 14 
0 13 
1 12 
0 11 
1 10 
0 10 

我想你是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

如果我使用或,代码继续运行,并没有结束。 – user3200392

+0

它基于你想要达到的逻辑。我已经在我的答案中更新了解释,可能会有所帮助。 –

+0

在第一个'while'循环中,您应该添加'max_speed + = 1'来更改max_speed值 –