int object is not iterable while trying to sum the digits of a number? [duplicate]

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.

Leave a Comment