You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报错'int' object has no attribute 'append'及分数打印问题排查

解决Python计分代码的'int' object has no attribute 'append'报错

嘿,这个报错的原因很好理解:你把score初始成了整数(score = len([])其实等价于score = 0),但后面却想用只有列表才有的append()方法——整数类型根本没有这个属性,所以直接触发了错误。

下面给你两种修正方案,按需选择就行:

方案1:用整数直接累加(最简洁的计分方式)

既然是计算总分,直接用整数累加是最直观的,完全没必要用列表:

score = 0  # 初始化分数为0

# 第一题
question1 = input("印度的首都是什么?")
answer1 = "delhi"
print("")
if question1.lower() == answer1:  # 加lower()让输入不区分大小写,更友好
    print("回答正确")
    score += 3  # 正确就加3分
    print('')
else:
    print('回答错误')
    print('')

# 第二题
question2 = input("特伦甘纳邦的首都是什么?")
answer2 = "hyderabad"
print("")
if question2.lower() == answer2:
    print("回答正确")
    score += 2
    print('')
else:
    print("回答错误")
    print('')

# 第三题
question3 = input("安得拉邦的首都是什么?")
answer3 = "amaraavathi"
print("")
if question3.lower() == answer3:
    print("回答正确")
    score += 3
    print('')
else:
    print("回答错误")
    print('')

print(f"你的总分数是:{score}")

方案2:用列表记录每道题得分(需要保留明细时用)

如果你想记录每道题的得分情况(比如正确加对应分,错误加0),那得把score初始化成空列表,最后再求和得到总分:

score = []  # 初始化为空列表

# 第一题
question1 = input("印度的首都是什么?")
answer1 = "delhi"
print("")
if question1.lower() == answer1:
    print("回答正确")
    score.append(3)
    print('')
else:
    print('回答错误')
    score.append(0)  # 错误就加0分
    print('')

# 第二题
question2 = input("特伦甘纳邦的首都是什么?")
answer2 = "hyderabad"
print("")
if question2.lower() == answer2:
    print("回答正确")
    score.append(2)
    print('')
else:
    print("回答错误")
    score.append(0)
    print('')

# 第三题
question3 = input("安得拉邦的首都是什么?")
answer3 = "amaraavathi"
print("")
if question3.lower() == answer3:
    print("回答正确")
    score.append(3)
    print('')
else:
    print("回答错误")
    score.append(0)
    print('')

total_score = sum(score)
print(f"你的总分数是:{total_score}")

额外优化小技巧

可以把题目、答案、分值做成一个列表,用循环处理,减少重复代码,后续加新题目也超方便:

score = 0
# 把所有题目信息存在一个列表里
quiz_items = [
    ("印度的首都是什么?", "delhi", 3),
    ("特伦甘纳邦的首都是什么?", "hyderabad", 2),
    ("安得拉邦的首都是什么?", "amaraavathi", 3)
]

# 循环处理每一道题
for question, correct_answer, points in quiz_items:
    user_input = input(question)
    print("")
    if user_input.lower() == correct_answer:
        print("回答正确")
        score += points
    else:
        print("回答错误")
    print("")

print(f"你的总分数是:{score}")

内容的提问来源于stack exchange,提问作者Vinay Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:16:32