繁体   English   中英

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

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

我三周前才开始为我的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")

感谢所有帮助! 谢谢!

元组用括号实例化,但它们用方括号索引,就像列表一样。 使用括号可以用括号前的变量名来“调用”一个函数,但显然变量名是一个元组,而不是函数名。 这就是为什么告诉您元组不可调用的原因,因为它不是,尽管您的代码正在尝试调用它。

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

这里的问题是您将bag定义为python元组,并使用错误的语法对其进行了访问。

具体来说,您是这样定义的:

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

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

bag("Knife")

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

你可能的意思是

bag[0]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM