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
maybe you're trying to
I just had this error because I wasn't using range()
You can try to change
for i in inp:
intofor i in range(1,inp):
Iteration doesn't work with a single int. Instead, you need provide a range for it to run.for .. in
statements expect you to use a type that has an iterator defined. A simple int type does not have an iterator.Don't make it a
int()
, but make it arange()
will solve this problem.try:
That will iterate over the characters in the string representation. Once you have each character you can use it like a separate number.
Side note: if you want to get the sum of all digits, you can simply do