【问题标题】:"'int' object is not iterable" error in for-loopfor循环中的“'int'对象不可迭代”错误
【发布时间】:2022-01-10 08:35:56
【问题描述】:

第 7 行代码错误

given_list2 = [5, 4, 4, 3, 1, -2, -3, -5]

total1 = 0

b = 0

for element in given_list2[b]:
    if b <= 0:
        break
    total1 += b

print(total1)

【问题讨论】:

  • 打印given_list2[b]的值,你看到就像你说的for i in 5: ...

标签: python for-loop


【解决方案1】:

你不能迭代一个整数,given_list2[b] 计算为索引 b 处的元素。遍历列表元素的正确语法是

for element in given_list2:
    if element <= 0:
        break
    total1 += element

或者您可以完全删除中断

for element in given_list2:
    if element > 0:
        total1 += element

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多