我正在尝试比较元组和列表中的项目但出现错误

I am trying to compare an item from a tuple and a list but get an error

我 3 周前才开始编码 python 游戏开发 class。我正在尝试比较元组中的项目和列表中的项目并获得响应。每当我 运行 代码时,我都会收到元组项不可调用的错误。我将 post 下面的代码。如果您知道出了什么问题,请帮助我。谢谢!

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")

感谢所有帮助!谢谢!

元组是用括号实例化的,但它们是用方括号索引的,就像列表一样。使用圆括号表示 "calling" 函数在圆括号前带有您的变量名,但显然该变量名是一个元组,而不是函数名。这就是为什么您被告知您的元组不可调用的原因,因为它不是,尽管您的代码正在尝试调用它。

检查您的条件 (if) 语句并将括号更改为方括号。这是一个常见且可以理解的错误。

这里的问题是您将 bag 定义为 python 元组并使用错误的语法访问它。

具体你是这样定义的:

bag = (" Knife ", " Gum ", " Water "," Bandages ", " Toilet Paper ")

然后您尝试像这样访问元组的第一个元素:

bag("Knife")

这是方法或函数调用的语法,因此它抱怨您的元组不可调用。

你的意思可能是

bag[0]

这将访问您包元组中的第一项。