【问题标题】:when i try to run this it says TypeError: list indices must be integers or slices, not str当我尝试运行它时它说 TypeError: list indices must be integers or slices, not str
【发布时间】:2017-08-24 21:27:17
【问题描述】:
import sys
def main():
    print("\t\tGame Menu\n")
    print("\t\tA - enter your name\n\t\tB - play the game\n\t\tC - quit")
    s = input("please enter your choice").upper()
    valid_option = ['A','B','C']
    while True:
        if s in valid_option['A']:#here
            n=input("please enter your name")
            print("I welcome thee valient night sir", n)
            print("\t\tGame Menu\n")
            print("\t\tA - enter your name\n\t\tB - play the game\n\t\tC - 
            quit")

        elif s in valid_option['B']:#here
            print("the game is starting,")
            print("\t\tGame Menu\n")
            print("\t\tA - enter your name\n\t\tB - play the game\n\t\tC - 
            quit")

        elif s in valid_option['C']:#and here 
            print("you have chosen to depart from our company, farewell 
            traveler")
            sys.exit()
main()

当我尝试运行它时,它显示 TypeError: list indices must be integers or slices, not str
请帮忙

【问题讨论】:

  • 你认为那行代码应该做什么?
  • 你用数字索引列表,正如错误所说。您希望它与“B”做什么?你是说 1 吗?

标签: python


【解决方案1】:

我完全不清楚你想用这条线实现什么:

if s in valid_option['A']:#here

也许这个更适合你:

if s == 'A':

【讨论】:

    【解决方案2】:

    valid_option 是list。要在列表中查找值,您必须使用索引表示法。

    valid_option[0] 等于 'A',valid_option[1] 等于 'B',valid_option[2] 等于 'C'。

    如果您想使用str 类型查找值,您的valid_option 变量需要是字典(即{} 而不是[]),而不是列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 2019-07-23
      • 2019-09-28
      • 2022-08-17
      • 2013-09-26
      • 1970-01-01
      • 2023-01-12
      相关资源
      最近更新 更多