Python报错TypeError:int与list间不支持>运算的解决求助
问题修复方案
错误原因
你代码里的核心问题是更新最高分的步骤中,错误地将highest赋值为整个scores列表,而非当前遍历到的分数s。第一次执行highest=scores后,highest变成了列表类型,后续循环里拿整数s和列表highest做比较,就会触发TypeError。你尝试给s加[0]完全没必要,因为s本身就是遍历列表得到的整数元素,不是列表。
修复后的代码
scores = input("Input a list of student scores ").split() for n in range(0, len(scores)): scores[n] = int(scores[n]) print(scores) # for loop way highest = 0 for s in scores: if s > highest: highest = s # 将scores替换为s,赋值当前的最高分 print(f"the highest score is {highest}")
额外优化建议
- 可以直接用Python内置函数
max()一行获取最高分,更简洁:print(f"the highest score is {max(scores)}") - 初始化
highest时,建议用列表的第一个元素而非0,避免所有分数为负数时结果不准确:highest = scores[0]
内容的提问来源于stack exchange,提问作者Rania F. Dweik
相关产品推荐
相关产品推荐

