【问题标题】:Python - AttributeError: 'str' object has no attribute 'append' - maths gamePython - AttributeError:'str'对象没有属性'append' - 数学游戏
【发布时间】:2018-05-16 10:51:15
【问题描述】:

试图让用户可以在高分列表中添加名称、分数以及用户完成游戏的难度。

def teacher_page():
    global scores, name, difficulties
    t_choice = None
    while t_choice !="0":
        print("\nWhat would you like to do?")
        print(
        """
        0 - Main Menu
        1 - Add a score
        2 - Remove a score
        3 - View highscores
        """
        )

        t_choice = input("Choice: ")
        print()

    #exit
        if t_choice == "0":
            main_menu()
    #add a score
        elif t_choice == "1":
            names = input("Name of the new user to add?\n")
            name.append(names)
            score = input("What did the user score?\n")
            scores.append(score)
            difficulty = input("And which difficulty did they complete it on?\n")
            difficulties.append(difficulty)
    #remove a score
        elif t_choice == "2":      
            names = input("Name of the user you want to remove?\n")
            if names in name:
                name.remove(names)          
            score = int(input("What did they score?\n"))
            if score in scores:
                scores.remove(score)
    #view highscores
        elif t_choice == "3":
            print("High Scores:")
            for score in scores:
                print(name, score, "on the difficulty ", difficulties)
    #if the t_choice does not = to 0,1,2,3
        else:
            print("Sorry but", t_choice, "isn't a vaild choice.")

但每次我想将用户添加到列表中时,我都会收到错误消息

AttributeError: 'str' object has no attribute 'append'

我看过一些例子,但不确定我哪里出错了。

【问题讨论】:

  • 字符串没有append 方法,如错误所示。您希望分数是一个字符串还是一个列表?也可以是name。使用跟踪显示确切的错误。
  • 那么问题是你认为的列表实际上是一个字符串。
  • Programming/Project/testing2.py", line 121, in teacher_page name.append(names) A​​ttributeError: 'str' object has no attribute 'append'
  • 这些全局变量scores, name是列表类型吗?
  • 那么您的name 对象的类型是什么?它没有在您的示例中定义,但显然它不是一个列表

标签: python math attributes scoring


【解决方案1】:

将变量初始化为列表右下方。

默认情况下,当您第一次为它们分配原始输入时,它们会成为字符串。

执行以下操作:

global scores, name, difficulties
scores=[]
name=[]
difficulties=[]

在全局声明期间。无需在函数内再次初始化。

【讨论】:

    猜你喜欢
    • 2015-03-08
    • 2015-02-17
    • 1970-01-01
    • 2018-06-22
    • 2015-08-16
    • 2017-08-14
    • 1970-01-01
    • 2013-11-05
    • 2018-12-01
    相关资源
    最近更新 更多