这是我的代码:
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]。然后我想将这些数字加在一起(我还没有开始做这件事,但我对如何做有些想法)。
137
[1,3,7]
但是,我不断收到此错误信息:
TypeError: 'int' object is not iterable
我做错什么了?
错误消息TypeError: 'int' object is not iterable表明您尝试迭代整数而不是可迭代对象(如列表或字符串)。在您的代码中,当您尝试使用 将整数转换为列表时会出现问题list(cow[n]),但此方法无效,因为cow[n]是整数。
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}.")
number1
number2
cow
number
str(number)
sum(digits)
此代码现在将正确地将每个数字分解为其数字,对其进行求和,然后打印结果。