【问题标题】:why am I getting argument of type 'int' is not iterable?为什么我得到'int'类型的参数是不可迭代的?
【发布时间】:2022-01-13 00:00:52
【问题描述】:

Python 编码新手在这里。我知道可能还会出现此错误的其他实例,并且我已尝试在堆栈溢出时读取它们,但对于我而言,以我的经验水平解码似乎太技术性了。有人可以帮助解释为什么这不起作用吗?我正在尝试使用 while 循环来要求用户输入一个数字。打印用户输入的所有数字的总和,如果用户输入 0,则退出 while 循环。

total = []
i = 1
total = int(input('enter a number:'))
while i in total > 0:
    total = int(input('enter a number:'))
    total = total + i
    if i == 0:
        break

【问题讨论】:

  • 您希望total = total + i 做什么?

标签: python loops input while-loop


【解决方案1】:
while i in total > 0:

使用运算符链接规则进行解析,这使其等效于:

while i in total and total > 0:

问题是total > 0测试; totallist,它正在尝试进行字典比较。你的另一个问题是:

total = total + i

list 不能与 int 一起添加。

固定的代码如下所示:

total = 0    # total should be an int, not a list to accumulate the sum
while True:  # The if check at the end makes it pointless to test or initialize i up front
    i = int(input('enter a number:'))
    total += i
    if i == 0:
        break

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 2023-02-20
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多