12. purify


#1



Why is my code not working?


def purify(numbers):
    new = ""
    for x in str(numbers):
        if x % 2 == 0:
            new += int(x)
    return new

print purify([1,2,3])


#2

Hi @sherifffuseini,

There are several issues here. You need to return a list. Here, you have initilialized new as a str ...

    new = ""

In this loop header, you are iterating through a str ...

    for x in str(numbers):

Work with numbers as a list instead. Then you will be able to process each item in numbers as an int. Consequently, this test will work correctly ...

            if x % 2 == 0:

#3

I have set new = [] but I dont get your "work with numbers as a list point". Can you explain that?


#4

Revise your loop, as follows ...

    for x in numbers:
        if x % 2 == 0:
            new.append(x)

Now, the for loop iterates through numbers as a list, rather than as a str. Within that loop, this statement places any number in that list that is even into new ...

            new.append(x)

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.