-4

This is my code

num = input()
if  not isinstance(num,int):
    print("wrong input")
    num = input()

However if I type letters from keyboard,the computer gives this error:

please input a num
q
Traceback (most recent call last):
File "ex11.py", line 8, in <module>
  num = input()
  File "<string>", line 1, in <module>
NameError: name 'q' is not defined
Jasper
  • 3,939
  • 1
  • 18
  • 35
Isaac
  • 689
  • 1
  • 6
  • 13

1 Answers1

3

In Python2, input immediately tries to eval the input. You should use raw_input to get a string. See the documentation.

It would also be more pythonic just to try to convert the user input to whatever format you need and handle exceptions that might occur:

inp = raw_input("enter a number:")
try:
  a = int(inp)
except ValueError:
  print "Could not convert input to int"
Jasper
  • 3,939
  • 1
  • 18
  • 35