Python - TypeError : tuple indices must be integers or slices, 不是 str

标签 python string python-3.x tuples runtime-error

<分区>

当试图在我的“商店”中购买东西时,shell 崩溃并显示“TypeError:元组索引必须是整数或切片,而不是 str”消息。此外,在我尝试购买东西之前,代码运行良好。

def store():
    os.system('cls')
    print("Welcome to the shop!")
    print("What would you like to buy?")
    print("1.) Greatsword - 40 gold")
    print("0.) Back")
    print(' ')
    option = input(' ')

    if option in weapons:
        if PlayerIG.gold >= weapons[option]:
            os.system("cls")
            PlayerIG.gold -= weapons[option]
            PlayerIG.weap.append(option)
            print("You have bought %s!" % option)
            option = input(' ')
            store()
        else:
            os.system('cls')
            print("You cannot afford this.")
            option = input(' ')
            store()

    elif option == "Back":
        start1()
    else:
      os.system("cls")
      print("That item does not exist.")
      option = input(' ')
      store()

然后我得到这个错误:

Traceback (most recent call last):
  File "C:\Users\Chris\Desktop\Amalgia Arena\AmalgiaArena.py", line 284, in <module>
    main()
  File "C:\Users\Chris\Desktop\Amalgia Arena\AmalgiaArena.py", line 60, in main
    start()
  File "C:\Users\Chris\Desktop\Amalgia Arena\AmalgiaArena.py", line 90, in start
    start1()
  File "C:\Users\Chris\Desktop\Amalgia Arena\AmalgiaArena.py", line 109, in start1
    store()
  File "C:\Users\Chris\Desktop\Amalgia Arena\AmalgiaArena.py", line 262, in store
    if PlayerIG.gold >= weapons[option]:
TypeError: tuple indices must be integers or slices, not str

我查看了其他具有相同错误的代码及其解决方案,但我对 Python 非常陌生,因此我无法弄清楚我需要修复什么。如果我需要发布更多代码,那么我会的。另外,我是这个站点的新手,所以如果你出于任何原因(坏问题、坏代码等)想要抨击我,那么请这样做。我愿意学习 :D

最佳答案

一个input的返回值是一个字符串,只要加上weapons[int(option)]就可以变成一个整数。

编辑:撤消上述操作。您所做的只是将 weapons 定义为元组而不是字典。只需将定义更改为 weapons = {'Greatsword', 40}

关于Python - TypeError : tuple indices must be integers or slices, 不是 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49077866/

相关文章:

python - set.add(x) 与集合 : What is faster? 中的 x

python - 属性错误:int object has no attribute name

python - 使用不同的参数同时运行相同的函数

c++ - C++ 中的 sprintf?

python - 以两个(或更多)其他变量为条件指定 `str` 的更优雅方式

python - 厨师和最高星级(CodeChef十月的长期挑战)

python - PHP 的 error_get_last() 函数的 Python 替代品是什么?

python - Jinja2 ASCII 转字符串

python - 提取一定数量字符之间的所有完整单词

r - 使用带有 grepl 和循环的名称列表从字符串中提取名称,并将它们添加到 R 中的新列