尝试除了奇怪的行为python 2.7

时间:2014-08-02 12:58:21

标签: python try-catch except

我有点困惑为什么'2'raw_input提示输入仍然在eval之后没有给出int错误(参见下面的代码)

correctInput = False

while not correctInput:
    try:
        raw_n = raw_input('Enter a non-negative number: ')
        print raw_n, 'before eval'
        n = eval(raw_n)
        print n, 'after eval'
    except NameError:
        print 'Wrong entry (NameError) ... try again'
    except SyntaxError:
        print 'Wrong entry (SyntaxError) ... try again'
    except NotImplementedError:
        print 'Wrong entry (NotImplementedError) ... try again'
    else:
        if type(n) != int:
            print 'Wrong entry (not int) ... try again'
        else:
            print 'Correct input'
            correctInput = True

输出如下:

Enter a non-negative number: '2'
'2' before eval
2 after eval
Wrong entry (not int) ... try again
Enter a non-negative number: 3
3 before eval
3 after eval
Correct input

但是,如果我检查终端

>>> x = eval('2')
>>> type(x)
<type 'int'>
>>> type(x) == int
True

任何想法发生了什么?

1 个答案:

答案 0 :(得分:2)

如果您在'2'提示符下输入raw_input - 字面意思撇号,2,撇号 - 您不会获得1个字符的字符串'2',就像您在输入Python源代码。你得到一个字符串,其内容是3个字符撇号,2,撇号。 eval将其评估为Python源代码,生成字符串'2'

不要输入'2',而是输入2