如何修复“int object is not iterable”

2024-04-20 03:47:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在'a'变量中添加所有整数,但是这个'a'变量既不是列表,也不是字符串,尽管其中有各种不同的整数。你知道吗

我正在编写一个Python程序,给定一个正整数num,由用户提供,打印所有除数的和。 我已经试着把这个'a'变量列成一个列表,但是同样的错误发生了

import math
num = int(input("Num: "))
a = num + 1 # because range excludes the last number
b = range(1, a) 
for i in (b):
    x = num / i
    if math.floor(x) == x:
            c = list(i)

我已经尝试将此“a”变量设置为列表,但是发生了相同的错误:“int object is not iterable”


Tags: 字符串用户import程序列表input错误range
2条回答

可以在循环外创建一个空列表:c = [],然后每次都通过c.append(i)将元素附加到列表中。你知道吗

list()创建一个新的列表,其参数必须是iterable(例如元组、另一个列表等)。如果您只传递一个数字i,它将不起作用。你知道吗

我想您要做的不是在每次循环迭代中创建一个新的列表,而是将i元素添加到一个已经存在的列表中。
您可以通过以下方式实现:

num = int(input("Num: "))
a = num + 1 # because range excludes the last number
b = range(1, a)
divisors = []  # create a new list where the results will be stored
for i in (b):
    x = num / i
    if math.floor(x) == x:
        divisors.append(i)  # add the number at the end of the list

如果要对所有除数求和,请使用:

sum(divisors)

一种更为“Pythonic”(当然,如果你不习惯list comprehensions的话,不一定更容易阅读)的方法可以达到同样的效果:

num = int(input("Num: "))
divisors_sum = sum(i for i in range(1, num + 1) if num//i == num/i)

我假设您在这里使用的是python3。在python3中,//是楼层划分,因此不必使用math.floor。有关///的更多详细信息,请参见this post。你知道吗

相关问题 更多 >