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?
How to Fix Int Object is Not Iterable. One way to fix it is to pass the variable into the range() function. In Python, the range function checks the variable passed into it and returns a series of numbers starting from 0 and stopping right before the specified number.
We can add a range() statement to our code to do this: for v in range(len(values)): This statement will create an iterable object with a list of values in the range of 0 and the number of items in the “values” list. Our code has successfully found all the instances of 3 in the list.
Since integers, individualistically, are not iterable, when we try to do a for x in 7 , it raises an exception stating TypeError: 'int' object is not iterable .
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With