1

I get a name error even though I'm just trying to put a string into a variable.

I am trying to do this on Python 2.7.11. Does anyone have anything that helps? Upgrading Python is not an option for me.

def translate(phrase):
    translation = ""
    for letter in phrase:
        if letter in " ":
            translation = translation + "@"
result = (input("enter a phrase you want encrypted: "))
result = translate(result)

This is the error that's shown:

Traceback (most recent call last):
  File "D:\hello\encrydecry\encryption1.py", line 158, in <module
>
    result = (input("enter a phrase you want encrypted: "))
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
glhr
  • 4,152
  • 1
  • 14
  • 24
PY_NEWBIE
  • 77
  • 4

2 Answers2

1

In Python 2, when you use input(), Python interprets the input. So when you type hello, hello is interpreted as a variable, and you're essentially doing result = hello. Hence the error NameError: name 'hello' is not defined.

One option is to simply type the input between quotes, so it will be interpreted as a string: 'hello'.

To avoid the input being interpreted altogether, you have to use raw_input() instead of input(), which doesn't interpret the user input and always returns a string:

result = raw_input("enter a phrase you want encrypted: ")
glhr
  • 4,152
  • 1
  • 14
  • 24
-2
def translate(phrase):
    translation = ""
    for letter in phrase:
        if letter in " ":
            translation = translation + "@"
result =raw_input("enter a phrase you want encrypted: ")
result = translate(result)