简体   繁体   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, i fixed it..for those who have the same problem and were on Grok Learning it was just an indention issue and I forgot to write int... Nvm,我已修复它..对于那些有相同问题并且在Grok Learning上的人来说,这只是一个缩进问题,我忘了编写int ...

You need to specify what to compare with for every comparison, so 您需要为每次比较指定要比较的内容,因此

elif distance <=2 and >=10 

should be: 应该:

elif distance <=2 and distance >=10:

(there are more clever ways to do this, but the above is the quickest fix) (有更聪明的方法可以做到这一点,但是以上是最快的解决方法)

So since you added a second question, I'll add a second answer :) 因此,既然您添加了第二个问题,我将添加第二个答案:)

In Python 3, the input() function always returns a string, and you cannot compare strings and integers without converting things first (Python 2 had different semantics here). 在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()

To convert a string to an integer value, use int(string) : 要将字符串转换为整数值,请使用int(string)

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

(also note that your code snippet above has an indentation issue -- you'll end up on the "if distance < 2" line whether you answer "Yes" or not. To fix this, you have to indent everything that should be in the "else" branch in the same way.) (还请注意,您上面的代码段存在缩进问题-无论您是否回答“是”,您最终都会在“ if distance <2”行中结束。要解决此问题,您必须缩进应包含在其中的所有内容同样地,“ else”分支)。

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

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