Python NameError - 用户输入后未定义名称

时间:2014-08-11 16:07:49

标签: python input

所有

我有以下代码:

val1 = str(input("Enter string element 1/3: "))
val2 = int(input("Enter integer element 2/3: "))
val3 = float(input("Enter float element 3/3: "))

lst = [val1, val2, val3]
tpl = (val1, val2, val3)
dict = {"First element: ":val1, "Second element: ":val2, "Third element: ":val3}

print("/n")
print("Here is your list: ", lst)
print("Here is your tuple: ", tpl)
print("Here is your dictionary ", dict)

print("/n")
val4 = input("Add a new str list element: ")
lst.append(val4)
print("Here is your new list ", lst) 

但我似乎得到了这个回报:

Traceback (most recent call last):
  File "C:/Python27/Test2", line 1, in <module>
    val1 = str(input("Enter string element 1/3: "))
  File "<string>", line 1, in <module>
NameError: name 'test' is not defined

然而,int和float都工作 - 那么为什么不串?它说'测试'没有定义,但我认为它是因为在用户输入单词后定义的?

非常感谢任何帮助。

此致

1 个答案:

答案 0 :(得分:1)

您希望在Python 2中使用raw_input而不是input

>>> float(input(": "))
: test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'test' is not defined

VS

>>> float(raw_input(": "))
: test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): test

input将其输入作为表达式进行评估,因此如果您在其提示符处输入test,它会尝试将其作为名称进行评估。

raw_input总是返回您键入的字符串str对象,因此您仍需要注意您键入的内容是您想要传递给它的任何值的输入值。