0

I am trying to implement a try exception in Python which when inputting a char/string instead of an int, catches the exception.

However, when inputting the letter 'a' the program crashes, returning the following error:

num = input('Enter integer number: ')   File "<string>", line 1, in
<module> NameError: name 'a' is not defined

This is my code:

if __name__ == '__main__':   #main function
    num = input('Enter integer number: ')
    try:
        num = int(num)
    except ValueError:
        print "Invalid input."
Maroun
  • 94,125
  • 30
  • 188
  • 241
Logan
  • 267
  • 3
  • 8
  • 18
  • 1
    Since you are in `python 2.x`(assuming that because of `print`), try using `raw_input` instead of `input` and don't add [tag:python-3.x] to your tags. – Lafexlos Apr 05 '16 at 08:29
  • If you are using pycharm, probably your interpreter is pointing to python 2.7. Try changing it to python3 and will solve the issue. You can change the interpreter in Preferences -> Project -> Python interpreter – Akhil Apr 01 '21 at 12:25

2 Answers2

2

You're trying to catch a ValueError but the function is raising a NameError instead. So you're no catching it. Try:

if __name__ == '__main__':   #main function
    num = input('Enter integer number: ')
    try:
        num = int(num)
    except Exception as e:
        print "Invalid input: {}".format(e.message)
Héctor Valverde
  • 1,089
  • 1
  • 14
  • 34
  • 2
    Actually, using `input` is the problem here. `input` acts as `eval` in python 2.x so that should be changed to `raw_input`. Casting int on char/string raises a ValueError which is what OP tries to achieve. – Lafexlos Apr 05 '16 at 08:33
  • You're right. Then, you can say then that there are at least two problems. The goal of the author is to 'implement a try exception in Python'. So I looked at the problem catching the exception. – Héctor Valverde Apr 05 '16 at 08:37
1

from the documentation input() interprets the given input.

https://docs.python.org/2/library/functions.html?highlight=input#input

so if you give the input as "a" it would interpret it as a string and proceed. since you are give the value as a, it expects a variable named a.

if you directly want to use the user input, as suggested in the comments by @Lafexlos use raw_input instead.

Anbarasan
  • 1,197
  • 13
  • 18