Solution: Even or Odd?#

Write a function that returns

  • True if the number is Even

  • False if the number is Odd.

Function definition#

def is_even(number):
    remainder = number % 2

    if remainder == 0:
        return True
    else:
        return False

The above structure can be simplified to just 1 line:

def is_even(number):
    return number % 2 == 0

Testing#

Check if your function returns the expected value using the cell below.

import unittest
from random import randint

class UnitTests(unittest.TestCase):
    def test_type(self):
        self.assertEqual(type(is_even(randint(-1000,1000))), type(False), 'The function should return a boolean operator')    
    def test_even(self):
        x = N = randint(-1000,1000)*2
        self.assertEqual(is_even(x), True, 'Should return `True` for %d' %x)
    def test_odd(self):
        x = N = randint(-1000,1000)*2 + 1
        self.assertEqual(is_even(x), False, 'Should return `False` for %d' %x)
        
unittest.main(argv=[''], verbosity=2,exit=False)
test_even (__main__.UnitTests) ... 
ok
test_odd (__main__.UnitTests) ... 
ok
test_type (__main__.UnitTests) ... 
ok

----------------------------------------------------------------------
Ran 3 tests in 0.002s

OK
<unittest.main.TestProgram at 0x7f4f2c946610>