Python 3语法E

2024-06-01 10:57:08 发布

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

  method = input("Is it currently raining? ")
if method=="Yes" :
  print("You should take the bus.")
else: distance = input("How far in km do you want to travel? ")
if distance == > 2:
    print("You should walk.")
elif distance ==  < 10 :
  print("You should take the bus.")
else: 
  print("You should ride your bike.")

Nvm,我修正了它。对于那些有同样问题的人来说,这只是一个缩进问题,我忘了写。。。在


Tags: theyouinputifisitelsemethod
2条回答

您需要为每次比较指定要比较的对象,因此

elif distance <=2 and >=10 

应该是:

^{pr2}$

(有更聪明的方法可以做到这一点,但以上是最快的解决方法)

既然你加了第二个问题,我就再加一个答案:)

在Python3中,input()函数总是返回一个字符串,如果不先进行转换,就不能比较字符串和整数(Python2在这里有不同的语义)。在

>>> distance = input()
10
>>> distance
'10' <- note the quotes here
>>> distance < 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() < int()

要将字符串转换为整数值,请使用int(string)

^{pr2}$

(还请注意,您上面的代码片段存在缩进问题,无论您是否回答“是”,您都将在“if distance<;2”行结束。要解决此问题,您必须以相同的方式缩进“else”分支中的所有内容。)

相关问题 更多 >