7B: Math

Lesson 7 has three parts A, B, C which can be completed in any order.

So far, we have performed math calculations using Python's operators +,  -, */ and the functions max and min. In this lesson we will see some more operators and functions and learn how to perform more complex calculations.

Math Operators

We have already seen how to use operators for addition (a + b), subtraction (a - b), multiplication (a * b) and division (a / b). We will now learn about three additional operators.

  • The power operator a ** b computes ab (a multiplied by itself b times). For example, 2 ** 3 produces 8 (which is 2×2×2).
  • The integer division operator a // b computes the "quotient" of a divided by b and ignores the remainder. For example, 14 // 3 produces 4.
  • The modulus operator a % b computes the remainder when a is divided by b. For example, 14 % 3 produces 2.

Example
The power, integer division, and modulus operators

Coding Exercise: Eggsactly
Egg cartons each hold exactly 12 eggs. Write a program which reads an integer number of eggs from input(), then prints out two numbers: how many cartons can be filled by these eggs, and how many eggs will be left over. For example, the output corresponding to 27 eggs is

2
3
since 27 eggs fill 2 cartons, leaving 3 eggs left over. Hint
You may enter input for the program in the box below.

The modulus operator is used for a variety of tasks. It can be used to answer questions like these ones:

Checking leap years is an example of divisibility testing; in the next exercise we ask you to write a program that performs divisibility testing in general.

Coding Exercise: Divisibility
Write a program that reads two positive integers a and b on separate lines. If a is divisible by b, print the message "divisible". Otherwise, print the message "not divisible". For example, when the input is

14
3
the program should print "not divisible". Hint
You may enter input for the program in the box below.

Math Functions

Python can compute most of the mathematical functions found on a scientific calculator.

  • sqrt(x) computes the square root of the number x.
  • exp(x) and log(x) are the exponential and natural logarithmic functions.
  • sin(x), cos(x), tan(x) and other trigonometric functions are available.
  • pi, the mathematical constant 3.1415...,  is also included.

When using Python's trigonometric functions, the angle x must be expressed in radians, not degrees.

Python includes such a large number of functions that they are organized into groups called modules. The above functions belong to the math module. Before using any functions from a module, you must import the module as shown in the example below. To use a function from a module you must type the module name, followed by a period, followed by the name of the function.

Example
Using functions from the math module

Coding Exercise: Pizza Circles
Your friends have eaten their square pizzas and are now ordering a round pizza. Write a program to calculate the area of this circular pizza. The input is a float r, which represents the radius in cm. The output should be the area in cm2, calculated using the formula  A=pi*r2. Use Python's pi feature instead of typing 3.1415...
You may enter input for the program in the box below.

Coding Exercise: Geometric Mean
The geometric mean of two numbers a and b is the number

\sqrt{ab}

(It is used to compare aspect ratios of display screens and describe the average growth rate of a population.) Write a program that reads two lines of positive float from input, and outputs their geometric mean.
Example: If the input is

5.0
20.0
then the output should be 10.0.
You may enter input for the program in the box below.

Putting it all together

As you saw in the previous exercise, you can build mathematical expressions by combining operators. Python evaluates the operators using the same "order of operations" that we learn about in math class:

Brackets first, then Exponents, followed by Division and Multiplication, then finally Addition and Subtraction,

which we remember by the acronym "BEDMAS". Integer division and modulus fit into the "Division and Multiplication" category. For example, the expression

3 * (1 + 2) ** 2 % 4
is evaluated by performing the addition in brackets (1+2 = 3), then the exponent (3 ** 2 = 9) , then the multiplication (3 * 9 = 27), and finally the modulus, producing a final result of 27 % 4 = 3.

Short Answer Exercise: Order of Operations
Compute the value of the Python expression

6 - 52 // 5 ** 2
Correct!

Integer division with negative numbers: The expressions a // b and int(a / b) are the same when a and b are positive. However, when a is negative, a // b uses "round towards negative infinity" and int(a / b) uses "round towards zero."

Example
Integer division with negative numbers

Integers and Floating-Point Numbers

The result of a mathematical expression is a number. As we saw previously, each number is stored as one of the two possible types:  int or float. The int type represents integers, both positive and negative, that can be as big as you want.

Python does not accept numbers written in the form 1 000 000 or 1,000,000. Type 1000000 instead.

The float type represents decimal numbers. Just as a simple calculator stores 1/3 as its approximate value 0.33333333, Python also stores decimal numbers as their approximate values.

Because Python uses approximations of decimal numbers, certain equations which are mathematically true may not be true in Python.
Example
Example
For this reason, it is important to allow some tolerance for these approximations when comparing numbers of type float. For example, in the internal grader used by this website, any float output is marked as correct if it is approximately equal to the expected answer.

We finish this lesson with some exercises.

Coding Exercise: Skill-Testing Question
As a "skill-testing question", you are given three integers and asked to add the first two numbers, then multiply the result by the third number. Write a program to read the three numbers and print out the correct answer. Hint
You may enter input for the program in the box below.

Coding Exercise: A Feat With Feet
For this program the input is a floating-point number representing a height measured in feet. Write a program that will output the equivalent height in centimetres using the conversion formula 1 foot = 30.48 cm. For example, if the input is 0.5, then the output should be 15.24.
You may enter input for the program in the box below.

Coding Exercise: Gravity
A parcel is thrown downward at a speed of v m/s from an airplane at altitude 11000 m. As it falls, its distance from the ground is given by the formula -4.9t2 - vt + 11000, where t is the time in seconds since it was dropped. Write a program to output the time it will take to reach the ground. The input to your program is the positive floating-point number v. The required time is given by the quadratic formula

\displaystyle{t=\frac{v-\sqrt{v^2-4(-4.9)(11000)}}{2(-4.9)}}

You may enter input for the program in the box below.

Congratulations! After completing these exercises you are ready to move to another lesson.