Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 873
eozzy Avatar asked Dec 21 '09 04:12

eozzy


People also ask

How do I fix int object is not iterable?

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.

How do you make an int object iterable in Python?

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.

Are integers iterable?

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 .

What are the iterable objects in Python?

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.


1 Answers

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.

like image 72
Alex Martelli Avatar answered Oct 16 '22 03:10

Alex Martelli