我刚刚开始为我的python游戏开发课程编写代码。我试图比较元组中的项目和列表中的项目并获得响应。每当我运行代码时,我都会收到元组项不可调用的错误。我将在下面发布代码。如果你知道什么是错的,请帮帮我。谢谢!
pick_up = "Yes"
i = 0
bag = ()
if not bag:
print("You are empty-handed.")
print("\nYou have found some items")
pick_up = input("\nDo you wish to pick them up? Yes/No")
if pick_up == "Yes":
print("You have successfully picked up the items!")
bag = (" Knife ", " Gum ", " Water ",
" Bandages ", " Toilet Paper ")
print("\nThese are the items in your bag:")
print(bag)
if pick_up == "No":
print("You remain empty handed")
howMany = len(bag)
print ("This is how many items are in your bag:", howMany)
while i < howMany:
print("\nThis is item:" + str(i) + bag[i])
i = i + 1
grab = "Yes"
j = 0
inventory = []
print ("\nYou have found some items")
grab = input("\nDo you wish to pick them up? Yes/No")
if grab == "Yes":
print("You have succesffuly picked up the items!")
inventory = [" Knife "," Napkins "," A McDonald's Drinking Straw "," A Shoe Lace ", " Banana "]
print("\nThese are the items in your inventory:")
print(inventory)
if grab == "No":
print("You are empty handed")
howMuch = len(inventory)
print("This is how many items are in your inventory:", howMuch)
while j < howMuch:
print("\nThis is item:" + str(j) + inventory[j])
j = j + 1
if inventory[0] == bag("Knife"):
print("We have a match!")
if inventory[0] != bag( 0 ):
print ("No like items")
感谢所有帮助!谢谢!
答案 0 :(得分:0)
元组用括号实例化,但它们用方括号索引,就像列表一样。使用括号传达&#34;呼叫&#34;在括号前面带有变量名称的函数,但显然变量名是元组,而不是函数名。这就是为什么你被告知你的元组不可调用,因为它不是,虽然你的代码试图调用它。
检查条件(if)语句并将括号更改为方括号。这是一个常见且可以理解的错误。
答案 1 :(得分:0)
这里的问题是你将bag定义为python元组并使用错误的语法访问它。
具体来说,你这样定义:
bag = (" Knife ", " Gum ", " Water "," Bandages ", " Toilet Paper ")
然后你试图像这样访问元组的第一个元素:
bag("Knife")
这是方法或函数调用的语法,因此它抱怨你的元组不可调用。
你可能意味着什么
bag[0]
将访问包元组中的第一项。