2/15 int object is not iterable


#1
def is_even(x):
    for i in x:
        #i = float(i)
        if i % 2.0 == 0:
            return True
        else: 
            return False

I keep getting errors saying that int object is not iterable. I commented out the third line because I was trying various things (in this case changing i into a float rather than an integer to see if that would make the python gods happy. It didn't.

I have tried searching the internet for the answer and found nothing that made sense.

My question isn't how to stop getting the error, it's what the error is actually saying and what the logical process behind debugging it would be.


#2

The for loop is completely unnecissary. This is the error because you cannot interate through a number. This is because a for loop iterates through lists of information, but can't through numbers.


#3

So if I were attempting to use this code, I would have to first convert my list of numbers to a list of numeric strings in order for it to be happy? We've been using loops with numbers fairly regularly throughout the python lessons...


#4

No, the problem is that what you put in isn't a list. You input 1 number to this function.


#5

So how do I make it take a list?


#7

I have already made a list and attempted to pass it through. The function won't take a list nor a single number.

Also, Python doesn't make you establish variables with var nor use semi colons since it uses white space. Right?


#8

Wow, sorry, mistake on my part! Lol, I was thinking you were doing JavaScript.


#9

Haha. No worries! It's easy to not notice in these forums!


#10

This is because it returns true or false. If it gets more than one in any given list it will error. It's best to run without the loop with single integers.


#11

Oooh! So since one list entry may return a False while the rest all return True it doesn't know what it should tell you? If I did want to make this work (as opposed to having it be some random exercise), would it work to have it create a dictionary and store the i as a key and the return as the variable? I assume that it would work just as well to have it return the results in a list form, but then you have results with no association.


#12

Yes this would work well, as long as you incremented the variable for each item in the list;


#13

Awesome! I'll try playing around with that later!

Thanks!


#14

Welcome! If you have any other ideas/problems make sure to mention @cadecodes! Looking forward to chatting ideas later.


#15

You could go the simple route, as I just figured out!
def is_even(x):
if x % 2 == 0:
return True
else:
return False


#16

I knew that, I just wanted it to work for passing lists through, which is why I was complicating it. Unless you can pass a list through the basic function...


#17

Thank you. This really helped.