-1

I have been trying to figure out what is wrong with the below code but in vain. The following code when run throws NameError when input is not a number. The error expected is ValueError. The except field should catch any error but does not.

print ("Enter a number")
num = input()
try:
        if int(num) > 10:
                print ("Number is greater than 10")
        elif int(num) == 10:
                print ("Number equal to 10")
        else:
                print ("Number is less than 10")
except:
        print ("Enter valid number")

output:

Enter a number
q
Traceback (most recent call last):
  File "1-try-ex.py", line 2, in <module>
    num = input()
  File "<string>", line 1, in <module>
NameError: name 'q' is not defined

The same code when checked on http://pythontutor.com/ gives expected behavior.

Please help to understand the issue.

Thanks in advance.

  • Is this the only code snippet which you are executing? I tried running the mentioned code, and I am getting the desired output. Have you declared a variable named `q` anywhere? – Nisarg Shah Mar 09 '21 at 08:13
  • 1
    This question is here: https://stackoverflow.com/questions/21122540/input-error-nameerror-name-is-not-defined – Johnny Mar 09 '21 at 08:13
  • You might want to [check-what-version-of-python-is-running-my-script](https://stackoverflow.com/questions/1093322/how-do-i-check-what-version-of-python-is-running-my-script) – Patrick Artner Mar 09 '21 at 08:15
  • The issue was that I thought I was running code on v3.x but it was 2.x as stated by Alex. – Ravi Pillai Mar 10 '21 at 09:25

1 Answers1

1

You think you're running Python 3 but you're actually running Python 2. input() in Python 2 is equivalent to eval(input()).

Alex Hall
  • 34,833
  • 5
  • 57
  • 89