2013-07-21 88 views
0
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,我固定it..for那些谁拥有了同样的问题,是对神交学习它只是一个缩进的问题,我忘了写INT ...Python 3的语法错误

+0

请不要更改你的问题中的代码在你收到答案后。它使答案毫无意义。 – RichieHindle

+0

@RichieHindle对不起,我不知道...我只需要仔细检查我复制了正确的代码...:0对不起 –

+0

我已经回滚到您收到答案的代码。 – Marcin

回答

2

所以因为你增加了第二个问题,我会添加第二个答案:)

在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 

(也注意到,上面的代码段有一个凹槽问题 - 你的“,如果距离结束< 2“行,不管你是否回答”是“,要解决这个问题,你必须以同样的方式缩进应该在”其他“分支中的所有内容。)

2

您需要指定如何处理每一个对比对比,所以

elif distance <=2 and >=10 

应该是:

elif distance <=2 and distance >=10: 

(有更聪明的方式做THI S,但上面是最快捷的修复)

+0

这很奇怪,因为在逻辑上,这是有道理的,但它仍然显示无效的语法错误! (可能是由于错误的缩进?) –

+0

对于读者来说,当然,但编译器并没有太多的假设... – Fredrik

+0

@fredrik我已经尝试了你所说的并修复了缩进,但它仍然显示错误的语法(这次指着10)......我做错了什么? :/ –