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
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:
+ Addition: 10 + 2 = 12.
- Subtraction: 12 - 2 = 10.
* Multiplication: 3 * 4 = 12.
/ Division: 12 / 3 = 4.
% Modulus: 13 % 3 = 1.
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
Why is the range range(1,21) and not range(20) or range(1,20)?
Why is i % 2 == 0: and not i % 2 = 0:
How can we modify the print function to include what number is odd or even?
Think about these before looking at the answers, maybe you did include some of these errors in your own code?
range(20) would return a sequence of numbers starting at 0 which you would then try to divide by 2! Python will return 0 for this so your function would say that 0 was even!
range(1,20) would return a sequence of numbers starting at 1 (good) all the way up to 19 so not 20 numbers.
Writing i % 2 = 0: would try to assign the value of 0 to the operator 2, 2 is now referencing 0. Remember that a single = assigns a value to a variable (identity), a double == checks for equality.
Modify the print function - remember that the print function take take more than one argument:
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...