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?
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:to:
Now that
inpis 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 aNameErrorsince you never initialize it. Presumably you wantn = 0before theforloop.Next, consider the difference between a character and an integer again. You now have:
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
to turn character
'7'into integer7, and so forth.