int object is not iterable while trying to sum the digits of a number?
I have this code:
inp = int(input("Enter a number:"))
for i in inp:
n = n + i;
print (n)
but it throws an error: 'int' object is not iterable
I wanted to find out the total by adding each digit, for eg, 110. 1 + 1 + 0 = 2. How do I do that?
Solution 1:
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.
Solution 2:
maybe you're trying to
for i in range(inp)
This will print your input value (inp) times, to print it only once, follow: for i in range(inp - inp + 1 ) print(i)
I just had this error because I wasn't using range()
Solution 3:
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.