Even or Odd (8kyu) [Python]
This is a very popular kata. Let's solve it!
Chek kata on Codewars
Create a function (or write a script in Shell) that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.
Modulus operator (%) operator. It returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
4 % 2 // 0 3 % 2 // 1
If the number is even it returns 0 and if the number is odd it returns 1. Which converts to false or true accordingly.
def even_or_odd(number): if number % 2 == 0: return "Even" else: return "Odd"
A little bit shorter version.
def even_or_odd(number): return 'Even' if number % 2 == 0 else 'Odd'
Alternatively, we can create an array with 'Even' and 'Odd' values and return the first or second element.
def even_or_odd(number): return ["Even", "Odd"][number % 2]