繁体   English   中英

Python 3语法错误

[英]Python 3 Syntax Error

  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,我已修复它..对于那些有相同问题并且在Grok Learning上的人来说,这只是一个缩进问题,我忘了编写int ...

您需要为每次比较指定要比较的内容,因此

elif distance <=2 and >=10 

应该:

elif distance <=2 and distance >=10:

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

因此,既然您添加了第二个问题,我将添加第二个答案:)

在Python 3中, input()函数始终返回一个字符串,并且如果不先进行转换就不能比较字符串和整数(Python 2在这里具有不同的语义)。

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

>>> distance = int(distance)
>>> distance
10 <- no quotes here
>>> distance < 10
False

(还请注意,您上面的代码段存在缩进问题-无论您是否回答“是”,您最终都会在“ if distance <2”行中结束。要解决此问题,您必须缩进应包含在其中的所有内容同样地,“ else”分支)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM