非常简单的问题,我想......我从字面上刚刚安装了Python,并正在测试一些初学者教程。Python - 简单的列表函数给出名称错误
我想创建一个菜单,允许您将项目添加到列表中,然后检查是否添加了它们:测试函数和过程中的列表。
#create empty list and define variables
firstlist = {'joe'}
additem = "test"
printthis = "test"
#create menu, add or check name
def menu():
#print what options you have
print "Add to list: type '1'"
print "Check for name: type '2'"
print "To exit program: type '3'"
return input ("Choose your option: ")
def addmenu():
additem = input("Name of list item: ")
firstlist.append(additem)
print additem, "has been appended"
def checkmenu():
printthis = input ("What are you looking for?: ")
if firstlist.has_key(printthis):
print "is in the list"
else:
print "is not in the list"
# Perform action
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
addmenu()
elif choice == 2:
checkmenu()
elif choice == 3:
loop = 0
elif choice > 3:
print "You made an incorrect selection"
继承人我的错误:
Traceback (most recent call last):
File "C:\Python27\testing python\tutorials\dictionaryselection", line 32, in <module>
addmenu()
File "C:\Python27\testing python\tutorials\dictionaryselection", line 15, in addmenu
additem = input("Name of list item: ")
File "<string>", line 1, in <module>
NameError: name 'TESTING' is not defined
不知道怎么回事...任何帮助,将不胜感激。下面
工作代码:转换到Python 3.x的
#create empty list and define variables
firstlist = ['Joe']
additem = "test"
printthis = "test"
#create menu, add or check name
def menu():
#print what options you have
print ("")
print ("Add to list: type '1'")
print ("Check for name: type '2'")
print ("To list the whole list '3'")
print ("To exit program: type '4'")
print ("-------------------------")
return input ("Choose your option: ")
def addmenu():
additem = input("Name of list item: ")
firstlist.append(additem)
print (additem, "has been appended")
def checkmenu():
printthis = input("What are you looking for?: ")
if printthis in firstlist:
print ("is in the list")
else:
print ("is not in the list")
def listlist():
print (firstlist[1])
# Perform action
loop = 1
choice = 0
while loop == 1:
choice = int(menu())
if choice == 1:
addmenu()
elif choice == 2:
checkmenu()
elif choice == 3:
listlist()
elif choice == 4:
loop = 0
elif (choice > 4):
print ("You made an incoorect selection")
你从哪里得到从这个例子的代码?这在多方面是错误的。'firstlist'可以是一个集合或者一个列表,但是定义对于后者来说是错误的,并且与名称不匹配。鉴于'print'语句的格式化,您使用的是Python 2,因此您通常必须使用raw_input而不是输入并将结果转换为专用。 'input()'和'eval(raw_input())'是一样的,这就是你得到这样一个错误的原因。 – mmgp
我根据其他示例制作了代码。只是帮助我弄清楚它是如何工作的。我不知道'set'是什么......还没有到达那里呢!我相信我正在使用Python 2.'eval(raw_input())'似乎没有摆脱错误。 –
@RickyMason他并不是说你应该使用'eval(raw_input())',他说这和你现在正在做的事情是一样的。由于您使用的是Python 2.x,所以只需使用'raw_input()'。 –