MrFronk
MrFronk

Reputation: 392

python user input error int vs string

I tried to search for this error, but i didnt find it so here it is:

I try to enter input in a python 3 script running in linux, which can only be 0-5. I do this using the following code:

    while True:
        type = input("Please choose a type:\n1) a\n2) b\n3) c\n4) d\n0) EXIT\n"))

        if type == "0":
            sys.exit()

        elif type == "1" or type == "2" or type == "3" or type == "4":
            print("You entered: %s" %type )
            break

        else:
            os.system("clear")
            print("Input entered is invalid, please try again.\n")

The program runs fine when I enter numbers, but when I enter a letter it crashes. Please help :(

Traceback (most recent call last):
  File "test.py", line 21, in <module>
    type = input("Please choose a type:\n1) a\n2) b\n3) c\n4) d\n0) EXIT\n"))   
  File "<string>", line 1, in <module>
NameError: name 'h' is not defined

Upvotes: 0

Views: 1124

Answers (1)

njzk2
njzk2

Reputation: 39397

input is equivalent to eval(raw_input(prompt))

Meaning your input is interpreted. Meaning that number, function, var will work, but not text.

Use raw_input instead. (see http://docs.python.org/2/library/functions.html#raw_input )

Nota: this is valid python 2, and you mention python 3. However, I think you are actually using python 2, as your prompt ends with a \n, which is included in python 3, and as your script works on python 3

Upvotes: 1

Related Questions