Creating a function - odd or even?

Andrew Virnuls
14th September 2016 at 16:41

Subject Genius, Andrew Virnuls, Creating a function - odd or even?

This article describes how to create a function to tell us whether a number is odd or even.  That might sound like a trivial task, but it's really a description of the process that students might go through when designing and implementing a function as part of their programming work.

Program Structure

There isn't much code required to determine whether a number is odd or even, so why not just include all of the code whenever you need it?  With a very short program, you could argue that that might be a sensible approach, but using functions for well-defined tasks is a good habit to get into. 

Functions should generally perform a single task, and having that code at the top of your program makes it easier to re-use (e.g. copy and paste into another program).  With more complex functions, especially where you apply the principle of data abstraction, functions make it easier to change the way something is done.  For example, if your program saves data, you could initially write a function that saves the information to a file, but then later change the function to instead save the information into a database - without the need to amend the rest of the program.

We will therefore create a function to tell us whether the number is odd or even.  It's a function, rather than a procedure, because we're expecting an answer.  In some programming languages (e.g. Visual Basic), functions and procedures are defined differently, whereas in others (e.g. Python and JavaScript), a procedure is just a function with no return value.

What Will The Answer Look Like?

So we're going to create a function to tell us whether a number is odd or even – but if we ask it whether a particular value is odd or even, what will the answer look like?

One option would be to return a string to describe the number, e.g. "odd" or "even".  That might be suitable for some applications, but strings are generally more complex to check.  The answer to the question of what the result should look like does depend on what you're going to do with the answer, but it might also affect the way that the function works.  In this case, generating a string as an answer would also make the function itself more complex.

For functions that don't calculate a numerical result, I quite like a Boolean answer – i.e. true or false.  Boolean values are easy to check and share some properties with integers – they are also usually straightforward to generate and process.

For this particular function, an answer of true or false doesn't really make sense if the question is Is x odd or even?, so I'm going to have to change the question slightly.  If I ask, instead, Is x odd?, then a Boolean response is clearer.

Now we've decided what the question is, and what the answer will look like, we can give the function an appropriate name that suggests what it does and the correct sense of the answer.  I'm going to call it isOdd().

How Do We Work It Out?

How do we know whether a number is odd or even?  We could think of the definition of an odd number, or think about some of the properties of odd and even numbers. 

Even numbers are multiples of two and odd numbers aren't.  Does that help?  One way in which it could help is that if we divide an even number by two, the result will be an integer, but if we divide an odd number by two (and we've got a friendly programming language) it will be a floating point number.  You could test the type of the result, e.g. using Python's type() command, but a common way to do the check is something like this:

def isOdd(x):

     if x/2 == int(x/2):

           return True


           return False

That's an arithmetic method, but being Computer Scientists, we probably want something a bit more "clever" (or possibly you'd like to use a technique from elsewhere in the curriculum to reinforce the students' understanding of it).

Another option would be to use modular arithmetic. The modulo function (% in Python and JavaScript) divides and gives us the remainder; dividing by two, therefore, will give a result of 0 for even numbers and 1 for odd numbers.  The following code would do the job:

def isOdd(x):

     if x % 2 = 1:

           return True


           return False

In most programming languages, however, true and false are like integer constants – usually with false being 0 and true being either 1 (e.g. Python and JavaScript) or -1 (e.g. Visual Basic).  It's easy, therefore, to convert the result into a Boolean value – e.g. by casting/converting with Python's bool() function.  The whole function becomes just one line:

def isOdd(x):

    return bool(x % 2)

Bitwise logic provides a third way of determining whether a number is odd or even.  If you look at the binary column headings that give the bits their place value, you will see that only one of them is not even, i.e. 1.  This means that the least-significant bit is only needed to represent odd numbers.  We can use bitwise AND to mask all but the right-most bit to inspect whether it is 0 or 1.  The bitwise AND operator in Python (and JavaScript) is &, so the function would look like this:

def isOdd(x):

    return bool(x & 1)

All of these techniques give the correct result provided that the value passed to isOdd() is an integer.  In most cases the function will return the wrong answer if you pass a floating point number and generate an error if you pass a string.  If the argument passed is to be user-generated then a full solution will also need to contain some validation.

What Can I Do With the Answer?

The function returns a Boolean value, so obviously we can test that with if to see whether it's true or false, e.g.

val = input("Give me a number: ")

if isOdd(val):

    print("That's odd.")


    print("That's even.")

We can also take advantage of the truth value's integer-like qualities to use the result in a calculation:

val = input("Give me an even number: ")

if isOdd(val):

    print("That's odd, but", val+isOdd(val), "is even.")


    print("That is even - well done!")

Excel Functions

You might be aware that macros in Microsoft Office can be written in, and are recorded using, Visual Basic for Applications (VBA).  What most people don't realise is that you can also use VBA to create functions for use in the spreadsheet itself, using the same principles that I've described above.

You need to add a module to your spreadsheet - press Alt + F11 to open the VBA editor, right-click on Microsoft Excel Objects, and choose Insert…

Excel already contents functions called isodd() and iseven(), so, instead, here's an example that you could use to check whether a number is prime:

Function isPrime(x As Double)

    Dim n As Integer, prime As Boolean

    If x < 2 Or Int(x) < x Then

        isPrime = False


        prime = True

        For n = 2 To Int(Sqr(x))

            If x Mod n = 0 Then prime = False       


        isPrime = prime

    End If

End Function

If you're not familiar with Visual Basic, values are returned using the name of the function rather than a return command.  Once you've added the function, you can use it in a cell in exactly the same way as a built-in function, e.g. =isPrime(A1) will tell you whether the value in cell A1 is prime.