I am using a while
loop inside a if
/ else
condition. For some reason under one condition the while loop does not work. The condition is shown in my code below. Under these conditions I would assume that the else
condition should be utilized and the weight
and the max_speed
should be decreased until both while
conditions are not valid anymore. What am I doing wrong?
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)
I think you are confused between or
and and
.
and
means that the expression will be True
if both condition satisfies. Where or
means any condition satisfies.
Now based on your code:
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:
Assuming that you need your weight=0
and max_speed=10
; You can do this ->
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))
Your output looks like ->
1 14
0 13
1 12
0 11
1 10
0 10
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.