这段代码有什么问题?(Python)

2024-03-29 13:53:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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,它会告诉你乘公共汽车


Tags: the用户youinputifisitprint
1条回答
网友
1楼 · 发布于 2024-03-29 13:53:37

为了进行数值比较,需要将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

相关问题 更多 >