为何我的Python函数出现TypeError: 'int' object is not iterable错误?
修复计算数字平方和的Python函数
你的代码存在两个问题:
- 关键字大小写错误:Python的循环关键字必须是小写的
for,你写成了For,这会导致语法错误。 - 参数类型不匹配:函数逻辑是迭代传入的参数,因此需要传入列表这类可迭代对象,但你调用时传了整数
5,整数无法被迭代,会触发TypeError。
修正后的代码:
def sum_of_squares(numbers): total = 0 for num in numbers: total += num ** 2 return total # 传入列表类型的参数 print(sum_of_squares([1, 2, 3, 4, 5])) # 输出:55
内容的提问来源于stack exchange,提问作者remas khalid
相关产品推荐
相关产品推荐

