简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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