CleverDev
CleverDev

Reputation: 487

Python remove odd numbers and print only even

user = int(raw_input("Type 5 numbers"))
even = []

def purify(odd):
    for n in odd:
        even.append(n)
        if n % 2 > 0:
            print n



print purify(user)

Hello I am a beginner and I would like to understand what is wrong with this code. The User chose 5 numers and I want to print the even numbers only. Thanks for helping

Upvotes: 1

Views: 5233

Answers (5)

Albert Zhao
Albert Zhao

Reputation: 9

def purify(list_number):
    s=[]
    for number in list_number:
        if number%2==0:    
            s+=[number]
    return s

Upvotes: -1

stanleyli
stanleyli

Reputation: 1477

filter would be the simplest way to "filter" even numbers:

output = filter(lambda x:~x&1, input)

Upvotes: 0

def purify(x):
    new_lst = []
    for i in x:
        if i % 2 == 0:
            new_lst.append(i)
    return new_lst

for search even

Upvotes: 0

beroe
beroe

Reputation: 12316

There are a few problems:

You can't apply int to an overall string, just to one integer at a time.

So if your numbers are space-separated, then you should split them into a list of strings. You can either convert them immediately after input, or wait and do it within your purify function.

Also, your purify function appends every value to the list even without testing it first.

Also, your test is backwards -- you are printing only odd numbers, not even.

Finally, you should return the value of even if you want to print it outside the function, instead of printing them as you loop.

I think this edited version should work.

user_raw = raw_input("Type some space-separated numbers")
user = user_raw.split()   # defaults to white space

def purify(odd):
    even = []
    for n in odd:
        if int(n) % 2 == 0:
            even.append(n)
    return even

print purify(user)

Upvotes: 2

Raab70
Raab70

Reputation: 721

raw_input returns a string and this cannot be converted to type int.

You can use this:

user = raw_input("Input 5 numbers separated by commas: ").split(",")
user = [int(i) for i in user]

Upvotes: 0

Related Questions