If a number is exactly divisible by 2 then it is an even number.
There is, however, not a straight off way of testing if a number is divisible by 2. Instead we can make the statement.If the remainder is zero when we divide two numbers then the first number is exactly divisible by the second.
which means that:If the remainder is zero when we divide a number by 2 then the number is even.
We can find the remainder when you divide two numbers by using the modulus operator (%
). For example:
>>> 10 % 3
1
>>> 12 % 3
0
>>> 24 % 5
4
Notes and Code | Outcome | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Testing for even numbersWrite a program that determines if a number is even by checking:if the remainder when the number is divided by 2 is zero then the number is even else the number is odd.
Notice that:
|
|
||||||||||||
A List and a LoopTo speed up the testing of different numbers, we can give the program a list of number to test.
Notice that:
Show Notes ▼
|
|
||||||||||||
Comparison OperatorsTesting for equality uses the== operator. The comparison operators are:
|
|||||||||||||
Exercise: Write a program to test if a number is greater than 10.
|
Code.
Show Notes ▼
Show Notes ▼
|
||||||||||||
Exercise: Write a program to test if a number is less than or equal to 22.
|
Code.
Show Notes ▼
Show Notes ▼
|
||||||||||||
Logical OperatorsWe can combine different comparisons with the logical operators
Example: Write a program to test if a number is between 5 and 50.
|
Code.
Show Notes ▼
|
||||||||||||
Exercise: Write a program check if a number is divisible by either 3 or 7. Use the test list:
|
|||||||||||||
Exercise: Write a program check if a number is divisible by both 3 and 7. Use the test list:
|
|||||||||||||
Practice: Write a program that prints the square root of positive and negative numbers. For example, for the square root of -4 you should print "2i". Use the test list:
|
|||||||||||||
Else IfWhat if we had multiple conditions to check, such as in assigning a letter grade to a numerical value or a piecewise defined function. Let's say the grade scheme was:
|
|
||||||||||||
ExerciseDraw a graph for the piecewise defined function below: $$ f(x) = \left\{ \begin{array}{ll} x & \quad x \lt -2 \\[.5em] 2x-1 & \quad -2 \le x \le 3 \\[.5em] -1 & \quad x > 3 \end{array} \right. $$ Ref: Remember how to draw a simple graph and plot points. |
The result could look something like this:
Show Notes ▼
|