小能豆

在尝试对数字进行求和时会出现“TypeError:'int'对象不可迭代”?

javascript

这是我的代码:

import math

print("Hey, lets solve Task 4 :)")

number1 = input("How many digits do you want to look at? ")
number2 = input("What would you like the digits to add up to? ")

if number1 == 1:
    cow = range(0,10)
elif number1 == 2:
    cow = range(10,100)
elif number1 == 3:
    cow = range(100,1000)
elif number1 == 4:
    cow = range(1000,10000)
elif number1 == 5:
    cow = range(10000,100000)
elif number1 == 6:
    cow = range(100000,1000000)
elif number1 == 7:
    cow = range(1000000,10000000)
elif number1 == 8:
    cow = range(10000000,100000000)
elif number1 == 9:
    cow = range(100000000,1000000000)
elif number1 == 10:
    cow = range(1000000000,10000000000)

number3 = cow[-1] + 1

n = 0
while n < number3:
    number4 = list(cow[n])
    n += 1

我想创建一个循环,以便列表中的每个元素都分解成每个字符。例如,假设数字137在列表中,那么它将变成[1,3,7]。然后我想将这些数字加在一起(我还没有开始做这件事,但我对如何做有些想法)。

但是,我不断收到此错误信息:

TypeError: 'int' object is not iterable

我做错什么了?


阅读 43

收藏
2024-09-25

共1个答案

小能豆

错误消息TypeError: 'int' object is not iterable表明您尝试迭代整数而不是可迭代对象(如列表或字符串)。在您的代码中,当您尝试使用 将整数转换为列表时会出现问题list(cow[n]),但此方法无效,因为cow[n]是整数。

为了解决这个问题并实现将个数字分解成数字然后求和的目标,您可以先将整数转换为字符串,然后创建其字符(数字)的列表。以下是您可以如何修改代码:

print("Hey, let's solve Task 4 :)")

# Get input from the user
number1 = int(input("How many digits do you want to look at? "))
number2 = int(input("What would you like the digits to add up to? "))

# Generate the range based on the number of digits
if number1 == 1:
    cow = range(0, 10)
elif number1 == 2:
    cow = range(10, 100)
elif number1 == 3:
    cow = range(100, 1000)
elif number1 == 4:
    cow = range(1000, 10000)
elif number1 == 5:
    cow = range(10000, 100000)
elif number1 == 6:
    cow = range(100000, 1000000)
elif number1 == 7:
    cow = range(1000000, 10000000)
elif number1 == 8:
    cow = range(10000000, 100000000)
elif number1 == 9:
    cow = range(100000000, 1000000000)
elif number1 == 10:
    cow = range(1000000000, 10000000000)

# Calculate the sum of digits for each number in the range
for number in cow:
    # Convert the number to string and then to a list of integers
    digits = [int(digit) for digit in str(number)]
    # Now you can sum the digits
    digit_sum = sum(digits)
    print(f"The number {number} has digits {digits} that sum to {digit_sum}.")

变更说明:

  1. 将输入转换为整数:获取输入后立即将number1其转换为整数。number2
  2. 迭代cow:我没有使用 while 循环,而是用 for 循环代替,直接迭代每个数字。
  3. 将数字转换为字符串:将每个数字转换number为字符串,str(number)并将其分解为各个数字。
  4. 数字列表理解:使用列表理解从数字创建整数列表。
  5. 数字总和:用于sum(digits)计算数字的总和。

此代码现在将正确地将每个数字分解为其数字,对其进行求和,然后打印结果。

2024-09-25