int object is not iterable?

前端 未结 11 835
天命终不由人
天命终不由人 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:24

    try:

    for i in str(inp):
    

    That will iterate over the characters in the string representation. Once you have each character you can use it like a separate number.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-01 11:29

    Side note: if you want to get the sum of all digits, you can simply do

    print sum(int(digit) for digit in raw_input('Enter a number:'))
    
    0 讨论(0)
  • 2020-12-01 11:30

    First, lose that call to int - you're converting a string of characters to an integer, which isn't what you want (you want to treat each character as its own number). Change:

    inp = int(input("Enter a number:"))
    

    to:

    inp = input("Enter a number:")
    

    Now that inp is a string of digits, you can loop over it, digit by digit.

    Next, assign some initial value to n -- as you code stands right now, you'll get a NameError since you never initialize it. Presumably you want n = 0 before the for loop.

    Next, consider the difference between a character and an integer again. You now have:

    n = n + i;
    

    which, besides the unnecessary semicolon (Python is an indentation-based syntax), is trying to sum the character i to the integer n -- that won't work! So, this becomes

    n = n + int(i)
    

    to turn character '7' into integer 7, and so forth.

    0 讨论(0)
  • 2020-12-01 11:33

    You can try to change for i in inp: into for i in range(1,inp): Iteration doesn't work with a single int. Instead, you need provide a range for it to run.

    0 讨论(0)
  • 2020-12-01 11:38

    for .. in statements expect you to use a type that has an iterator defined. A simple int type does not have an iterator.

    0 讨论(0)
提交回复
热议问题