Why am I getting TypeError: 'int' object is not iterable in my code?

Viewed 1349

I'm designing a program that prints prime factors of a number.

Here is the code:

while True:
    x = int(input("Enter a positive number: "))
    if x >= 0:
        break

ranger = list(range(1, x+1))
counter = 0

#The first for loop checks if the number is a factor
for i in ranger:
    if x % i == 0:
        #The second for loop checks if the number is prime
        for element in range(1, i+1 ):
            if i % element == 0:
                counter += 1
                if counter == 2:
                    prime_factors = []
                    prime_factors += i
                #Counter having a value of 2 means the number is prime

print(prime_factors)

I keep getting the error:

Traceback (most recent call last):
  File ".\primefactors.py", line 18, in <module>

    prime_factors += i
TypeError: 'int' object is not iterable

But I don't seem to understand why I am getting this error.

3 Answers

It should be prime_factors.append(i), as you add to lists using .append(), not the addition operator :)

(python will throw errors if you try to + a list and an int as it's not possible to add them together)

The list addition operator is defined only on two lists, not on a list and an integer. Python was trying to do a list.__add__ on prime_factors and i, which includes iterating through the elements of i. That's where you got the error.

The correct command would be

prime_factors.append(i)

With that change, your program correctly prints only the lowest prime factor. You also need to move your initializations and checks to the proper places:

  • set prime_factors to the empty list only at the start of your program.
  • set counter back to 0 for each suspected prime factor.
  • check the value of counter only after you've looked at all smaller numbers.

When the left operand of += is a list, python expects an iterable on the right side. You can use append instead, or prime_factors +=[i]. Also, it looks like you screwed up the identation or something; your present code doesn't make any sense. For instance, your prime_factors +=i line is always preceded by prime_factors = []. If you were to replace += with append, you would end up with those two line having the same functionality as if you had one line that just said prime_factors = [i].

Related