麻烦简单的Python代码

时间:2009-09-08 18:39:48

标签: python

我正在学习Python,而我在使用这段简单的代码时遇到了麻烦:

a = raw_input('Enter a number: ')

if a > 0:
    print 'Positive'
elif a == 0:
    print 'Null'
elif a < 0:
    print 'Negative'

它的效果很好,除了它总是打印'正',无论我输入正数还是负数或零。我猜这是一个简单的解决方案,但我找不到它; - )

提前致谢

6 个答案:

答案 0 :(得分:7)

那是因为a是输入的字符串。在进行数值比较之前,请使用int()将其转换为整数。

a = int(raw_input('Enter a number: '))
if a > 0:
    print 'Positive'
elif a == 0:
    print 'Null'
elif a < 0:
    print 'Negative'

或者,input()会为您进行类型转换。

a = input('Enter a number: ')

答案 1 :(得分:7)

因为你正在使用raw_input,所以你得到的值是String,它总是被认为大于0(即使字符串是'-10')

相反,请尝试使用input('Enter a number: ') and python will do the type conversion for you.

The final code would look like this:

a = input('Enter a number: ')
if a > 0:
    print 'Positive'
elif a == 0:
    print 'Null'
elif a < 0:
    print 'Negative'

However, as a number of folks have pointed out, using input() may lead to an error because it actually interprets the python objects passed in.

A safer way to handle this can be to cast raw_input with the desired type, as in:

a = input('Enter a number: ')
if a > 0:
    print 'Positive'
elif a == 0:
    print 'Null'
elif a < 0:
    print 'Negative'

但要注意,你仍然需要在这里做一些错误处理以避免麻烦!

答案 2 :(得分:7)

扩展我对accepted answer的评论,以下是我的做法。

value = None
getting_input = True

while getting_input:
    try:
        value = int(raw_input('Gimme a number: '))
        getting_input = False
    except ValueError:
        print "That's not a number... try again."

if value > 0:
    print 'Positive'
elif value < 0:
    print 'Negative'
else:
    print 'Null'

答案 3 :(得分:5)

raw_input 

返回一个字符串,因此您需要先将a字符串转换为整数:a = int(a)

答案 4 :(得分:2)

raw_input存储为字符串,而不是整数。

在执行比较之前尝试使用a = int(a)

答案 5 :(得分:1)

原始输入将返回一个字符串,而不是整数。要转换它,请尝试在raw_input语句后立即添加此行:

a = int(a)

这会将字符串转换为整数。但是,你可以通过给它非数字数据来崩溃它,所以要小心。

相关问题