TypeError in Python Programming
<p>I wrote the following program for square each digit of a number. But, it is showing an error as "int" object is not iterable.</p>

<pre><code>def square_digits(num):

a = 1
for i in num:
  a = i * i        
  return a

result = square_digits(12)
print(result)
</code></pre>

<p>first off, this is how to fix your code:</p>

<p>If you want a list of squared numbers beginning from 1 to num:</p>

<pre><code>`
def square_digits(num):
    # initialize an empty list
    a = []
    # why num + 1 when you want numbers until num? check out this link for an explanation
    # on how to use and the different uses of the range() function
    # http://pythoncentral.io/pythons-range-function-explained/
    for i in range(1, num + 1):
        # square the numbers beginning from 1,
        squared_i = i * i
        # and then add the result to the list that we have
        a.append(squared_i)
    # after everything is done, return the list
    return a

result = square_digits(12)
print(result)
`
</code></pre>

<p>In your earlier example, you were basically trying to make this work:</p>

<pre><code>`
for i in 12:
    square_result = i * i
    print ("the square of " + str(i) + " is " + str(square_result))
`    
</code></pre>

<p>which isn't going to work because you're trying to iterate on 12, which is an int</p>

<p>However if you do this:</p>

<pre><code>`
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]:
    square_result = i * i
    print ("the square of " + str(i) + " is " + str(square_result))
`    
</code></pre>

<p>then you're going to have better results, because you're iterating on a list.</p>

<p>the shorter way of doing the above example is:</p>

<pre><code>`
num = 12
for i in range(1, num + 1):
    square_result = i * i
    print ("the square of " + str(i) + " is " + str(square_result))
`    
</code></pre>

<p>which should also work because <code>range(1, num + 1)</code> should return the list <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]</code> if <code>num = 12</code>
in python2. In python3 however, the range function will not return a list, instead it will return something that can be iterated upon like a list for the purpose of this question.</p>

<p>However, I'm not certain if it's a list your looking for as a result, if not, feel free to clarify your question, hopefully others can also chime in.</p>

python