int object is not iterable?

前端 未结 11 856
天命终不由人
天命终不由人 2020-12-01 11:19
inp = int(input(\"Enter a number:\"))

for i in inp:
    n = n + i;
    print (n)

... throws an error: \'int\' object is not iterable<

11条回答
  •  不思量自难忘°
    2020-12-01 11:27

    Take your input and make sure it's a string so that it's iterable.

    Then perform a list comprehension and change each value back to a number.

    Now, you can do the sum of all the numbers if you want:

    inp = [int(i) for i in str(input("Enter a number:"))]
    print sum(inp)
    

    Or, if you really want to see the output while it's executing:

    def printadd(x,y):
        print x+y
        return x+y
    
    inp = [int(i) for i in str(input("Enter a number:"))]
    reduce(printadd,inp)
    

提交回复
热议问题