将input()分配给变量时发生NameError(Python2.7.11)

时间:2019-04-20 09:58:32

标签: python python-2.7

即使我只是试图将字符串放入变量中,我也遇到名称错误。

我正在尝试在Python 2.7.11上执行此操作。有人有什么帮助吗?升级Python对我来说不是一个选择。

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

这是显示的错误:

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

2 个答案:

答案 0 :(得分:1)

在Python 2中,当您使用input()时,Python会解释输入。因此,当您输入hello时,hello被解释为一个变量,实际上就是在进行result = hello。因此出现错误NameError: name 'hello' is not defined

一种选择是仅在引号之间键入输入,因此它将被解释为字符串:'hello'

为避免完全解释输入,您必须使用raw_input()而不是input(),它不会解释用户输入,并且始终返回字符串:

result = raw_input("enter a phrase you want encrypted: ")

答案 1 :(得分:-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)