Python - TypeError:元组索引必须是整数或切片,而不是str [duplicate]

问题描述 投票:0回答:1

这个问题在这里已有答案:

当我试图在我的'shop'中购买东西时,shell崩溃时出现“TypeError:tuple indices必须是整数或切片,而不是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

python string python-3.x tuples runtime-error
1个回答
0
投票

input的返回值是一个字符串,只需添加weapons[int(option)]即可更改为整数。

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

© www.soinside.com 2019 - 2024. All rights reserved.