非常簡單的問題,我想......我從字面上剛剛安裝了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()'。 –