inp = int(input("Enter a number:"))
for i in inp:
n = n + i;
print (n)
... 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?
Thanks
inp = int(input("Enter a number:"))
for i in inp:
n = n + i;
print (n)
... 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?
Thanks
As ghills had already mentioned
When you are looping through something, keyword is "IN", just always think of it as a list of something. You cannot loop through a plain integer. Therefore, it is not iterable.
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:
Or, if you really want to see the output while it's executing:
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
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 aNameError
since you never initialize it. Presumably you wantn = 0
before thefor
loop.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.Well, you want to process the string representing the number, iterating over the digits, not the number itself (which is an abstract entity that could be written differently, like "CX" in Roman numerals or "0x6e" hexadecimal (both for 110) or whatever).
Therefore:
Note that the
n = 0
is required (someplace before entry into the loop). You can't take the value of a variable which doesn't exist (and the right hand side ofn = n + int(digit)
takes the value ofn
). And ifn
does exist at that point, it might hold something completely unrelated to your present needs, leading to unexpected behaviour; you need to guard against that.This solution makes no attempt to ensure that the input provided by the user is actually a number. I'll leave this problem for you to think about (hint: all that you need is there in the Python tutorial).
One possible answer to OP-s question ("I wanted to find out the total by adding each digit, for eg, 110. 1 + 1 + 0 = 2. How do I do that?") is to use built-in function divmod()