aaawww qqq
aaawww qqq

Reputation: 11

how to check number odd even python?

How do I show even and odd in print (x ,"is" )?

num_list = list(range(1, 51))
odd_nums = []
even_nums = []

for x in num_list:    
    if x % 2 == 0:        
        even_nums.append(x)
    else:       
        odd_nums.append(x)
    print (x ,"is" )

Upvotes: 0

Views: 2750

Answers (5)

Mohan. A
Mohan. A

Reputation: 419

Sol 1 - Using list comprehension -

print([("even" if x%2 == 0 else "odd") for x in range(10)])

Sol 2 - Using list comprehension -

print([x for x in range(10) if x%2 ==0])

Sol 3 - Using dictionary comprehension -

di = {x:("even" if x%2 == 0 else "odd") for x in range(10)}
print(di)

Sol 4 - Using filter() -

li = list(range(20))
print(list(filter(lambda x: x%2 == 0,li)))
print(list(filter(lambda x: x%2 == 1,li)))

Upvotes: 1

Rafał
Rafał

Reputation: 705

You can use shortcut if at the end of code

num_list = list(range(1, 51))
odd_nums = []
even_nums = []

for x in num_list:
    is_odd = x % 2
    if  is_odd:        
        odd_nums.append(x)
    else:       
        even_nums.append(x)
    print (x ,"is",  "odd" if is_odd else "even" )

Upvotes: 0

ikuamike
ikuamike

Reputation: 335

Your code already works properly all you could do is update your print statement like this.

num_list = list(range(1, 51))
odd_nums = []
even_nums = []

for x in num_list:    
    if x % 2 == 0:        
        even_nums.append(x)
        print (x ,"is even" )
    else:       
        odd_nums.append(x)
        print (x ,"is odd" )

Upvotes: 0

I'mDoneOK
I'mDoneOK

Reputation: 39

As easy as adding this:

num_list = list(range(1, 51))
odd_nums = []
even_nums = []

for x in num_list:    
    if x % 2 == 0:        
        even_nums.append(x)
        print (x ,"is even" )
    else:       
        odd_nums.append(x)
    print (x ,"is odd" )

Upvotes: 0

Dinu Kuruppu
Dinu Kuruppu

Reputation: 165

You are Already checking it, if you wanna display "Odd" or Even" you can simply put a print statement within if-else statement;

num_list = list(range(1, 51))
odd_nums = []
even_nums = []

for x in num_list:    
    if x % 2 == 0:        
        even_nums.append(x)
        print (x ,"is a even number")
    else:       
        odd_nums.append(x)
        print (x ,"is a odd number")

Upvotes: 0

Related Questions