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.appe
Solution 1:
Sol 1 - Using list comprehension -
print([("even"if x%2 == 0else"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 == 0else"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)))
Solution 2:
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")
Solution 3:
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" )
Solution 4:
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" )
Solution 5:
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 % 2if is_odd:
odd_nums.append(x)
else:
even_nums.append(x)
print (x ,"is", "odd"if is_odd else"even" )
Post a Comment for "How To Check Number Odd Even Python?"