0

I've recently been creating a text adventure game but almost immediately ran into a problem with the input. It is giving me error messages when I use strings instead of integers. There is probably an obvious reason that this is happening and I'm just not seeing it.

Here's an example:

    b = input("Do you like video games? y/n")
    if b == "y":
        print("Good For You!")
    if b == "n":
        print("What!? (Just joking)")

I've researched a lot and this seems to be working for most other people. But when I use it I get this error:

    Do you like video games? y/ny
    Traceback (most recent call last):
      File "/home/ubuntu/workspace/Test.py", line 1, in <module>
        b = input("Do you like video games? y/n")
      File "<string>", line 1, in <module>
    NameError: name 'y' is not defined

As you can see, it says that y is not defined. I'm okay with basic python programming, but I'm horrible at reading error messages. It would be great if you guys could give me an answer. Thank you!

4
  • 2
    You're not on Python 3 like you think you are. Commented Jul 26, 2016 at 22:33
  • Are you sure you're using Python 3? For me, that error only appears if I run your code in Python 2. Commented Jul 26, 2016 at 22:33
  • If you try to run your code on linux make sure you use python3 Test.py to run it from terminal Commented Jul 26, 2016 at 22:34
  • 1
    Possible duplicate of NameError from Python input() function or this or this or this... Commented Jul 26, 2016 at 22:41

2 Answers 2

0

That error from using the input function is typical of Python 2 and not Python 3. I suspect you are actually using Python 2.

To determine which version of python runs when you use the python command:

$ python --version
# example output: Python 2.7.3

To make sure you run your script using python 3, do:

$ python3 scriptname.py


Python 2

In Python 2, to get user input, you actually need to use the function raw_input, as the input function tries to evaluate the user's input as if it were python code.

So when the user inputs 'y', the input function then tries to evaluate the expression y, which in this case would mean the variable named y, which doesn't exist.

So for python 2, your code should look like:

b = raw_input("Do you like video games? y/n")
# etc


Python 3

In python 3, the input function takes the place of raw_input, so your code would work as-is.

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

Comments

0

You are actually using Python 2, not 3 unfortunately. Since you are using input() in Python 2, input() actually is evaluating the expression, instead of being Python 3's equivalent for Python 2's raw_input(). input() in this case, failed to find a variable with the name y (the input) and raised the error.

Simply change your Python version from 2.x to 3.x and you should be fine. If you are sticking with Python 2 though, use raw_input() instead:

b = raw_input("Do you like video games? y/n")

Comments