Pagol
Pagol

Reputation: 251

try except strange behavior python 2.7

I'm a little confused why an input of '2' to the raw_input prompt still gives not int error after eval (see code below)

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

The output looks like:

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

However, if I check on terminal

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

Any ideas what is going on?

Upvotes: 1

Views: 199

Answers (1)

user2357112
user2357112

Reputation: 280207

If you enter '2' at the raw_input prompt - literally apostrophe, 2, apostrophe - you don't get the 1-character string '2', as you would if you typed that into Python source code. You get a string whose contents are the 3 characters apostrophe, 2, apostrophe. eval evaluates that as Python source code, producing the string '2'.

Instead of typing '2', type 2.

Upvotes: 2

Related Questions