python整形不可迭代,Python-TypeError:“ int”对象不可迭代

Here's my code:

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

I am looking to make a loop so that for each element in the list, it will get broken down into each of it's characters. For example, say the number 137 was in the list then it would be turned into [1,3,7]. Then I want to add these numbers together (I haven't started that bit yet but I have some idea of how to do it).

However, I keep getting the error message

TypeError: 'int' object is not iterable

when I try and run this.

What am I doing wrong?

解决方案

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1

>>> list(a)

Traceback (most recent call last):

File "", line 1, in

TypeError: 'int' object is not iterable

>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1

>>> [a]

[1]

>>>

Also, I wanted to address two things:

Your while-statement is missing a : at the end.

It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137

>>> a = str(a)

>>> # This way is more common and preferred

>>> sum(int(x) for x in a)

11

>>> # But this also works

>>> sum(map(int, a))

11

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值