0

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
3
  • you should not use 'type' as a variable name because you are overriding the builtin function Commented Oct 31, 2012 at 13:50
  • Your code and the traceback don't match. The last line of the traceback says "name 'h' is not defined" but I don't see any 'h' in your code. Commented Oct 31, 2012 at 14:03
  • 2
    @F.C. : h is the typed input, which is evaluated by input, which doesn't find it to be evaluable, hence the error. Commented Oct 31, 2012 at 14:24

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it seems linux runs 2.x by default, when i need to use python 3. I dont want to use the python 2 variants however, i need to install python 3 on linux :)
@MrFronk Most modern linux distros will have python 3 installed as well - generally with the command python3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.