design, write and debug programs that accomplish specific goals, including controlling or simulating physical systems; solve problems by decomposing them into smaller parts.

use logical reasoning to explain how some simple algorithms work and to detect and correct errors in algorithms and programs

6.4a

LO: To use the modulus operator (%).

We have used several different operators in Python so far so let's recap them as we introduce a new one:

The modulus operator returns the remainder of division, in this example 13 % 3 = 1 because 13 / 3 = 4 remainder 1.

Let's write a useful function using the modulus operator, a function to check if a number is odd or even. You might want to have a go at writing this yourself first - an even number would have n % 2 = 0 (no remainders if divided by two):





#define a function to take in a number
def odd_or_even(number):
#use if statements to evaluate the number
    if number % 2 == 0:
        print("even")
        return True
    else:
        print("odd")
        return False

#call the function
odd_or_even(3)

			

Notice that return statements have been included - you can imaging a program that will act in different ways if the number was odd or even, if the return value is True or False it can be evaluated in other conditional statements.

Can you improve on this code using a for loop so it will check a range of numbers (that was a clue).

Have a look at this flowchart first:


#let's start with a for loop that will check numbers from 1 to 20
for i in range(1,21):
    if i % 2 == 0:
        print("even")
        return True
    else:
        print("odd")
        return False
    

			

Some questions:

Think about these before looking at the answers, maybe you did include some of these errors in your own code?




for i in range(1,21):
    if i % 2 == 0:
        print(i, "is even")
        return True
    else:
        print(i, "is odd")
        return False

			

Could you turn this code into a function that allows the range of numbers checked to change (1 to x)?

Could you turn that function into a program that asks for user input to change the range of numbers checked?




Possible solutions are available in the code examples below...

Code Examples

Resources