rain = input("Is it currently raining? ")
if rain == 'Yes':
print("You should take the bus.")
elif rain == 'No':
travel = input("How far in km do you need to travel? ")
if travel <= '2' and >= '10':
print("You should ride your bike.")
elif travel > '2':
print("You should walk.")
elif travel < '10':
print("You should take the bus.")
在此代码中,它会询问用户正在下雨,如果要下雨,它将告诉用户乘公共汽车去,但是如果您说不,那不是下雨,它会询问您需要行驶多远,以公里为单位如果它小于2,它将告诉您应该步行;如果它大于2但小于10,它将告诉您应该骑自行车;最后,如果它大于10,它将告诉您乘坐公共汽车。
您需要将travel
转换为数字才能进行数字比较。否则,它将进行字典分析比较,例如在这种情况下为'9' > '10'
。
并且要与两个数字进行比较,您必须再次指定变量。您似乎也完全没有进行比较。
travel = int(input("How far in km do you need to travel? "))
if travel >= 2 and travel <= 10:
print("You should ride your bike.")
elif travel < 2:
print("You should walk.")
elif travel > 10:
print("You should take the bus.")
[travel >= 2 and travel <= '10'
也可以简化为2 <= travel <= 10