[python] int object is not iterable?

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

This question is related to python int loops

The answer is


You can try to change for i in inp: into for i in range(1,inp): Iteration doesn't work with a single int. Instead, you need provide a range for it to run.


As ghills had already mentioned

inp = int(input("Enter a number:"))

n = 0
for i in str(inp):
    n = n + int(i);
    print n

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.


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()

num = int(input('Enter a number: ')
nums_sum = 0

while num:
    num, reminder = divmod(num, 10)
    nums_sum += reminder

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:

inp = [int(i) for i in str(input("Enter a number:"))]
print sum(inp)

Or, if you really want to see the output while it's executing:

def printadd(x,y):
    print x+y
    return x+y

inp = [int(i) for i in str(input("Enter a number:"))]
reduce(printadd,inp)

for .. in statements expect you to use a type that has an iterator defined. A simple int type does not have an iterator.


try:

for i in str(inp):

That will iterate over the characters in the string representation. Once you have each character you can use it like a separate number.


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:

inp = input('Enter a number:')

n = 0
for digit in inp:
     n = n + int(digit)
     print(n)

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 of n = n + int(digit) takes the value of n). And if n 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).


Side note: if you want to get the sum of all digits, you can simply do

print sum(int(digit) for digit in raw_input('Enter a number:'))

maybe you're trying to

for i in range(inp)

This will print your input value (inp) times, to print it only once, follow: for i in range(inp - inp + 1 ) print(i)

I just had this error because I wasn't using range()


Don't make it a int(), but make it a range() will solve this problem.

inp = range(input("Enter a number: "))

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true