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.
  • ceil(x) computes the ceiling of x as a float, the smallest integer value greater than or equal to x.
  • floor(x) computes the floor of x as a float, the largest integer value less than or equal to x.
  • pi, the mathematical constant 3.1415...,  is also included.

If you’d like to see what all math functions available can do, make sure to check the official documentation at https://docs.python.org/2/library/math.html

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.

Math Functions Example

Coding Exercise

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 ...

Pizza Exercise

Random Numbers

You can produce random numbers in python with the random module.

random.random() returns a random float in the range of 0.0 and 1.0. 1.0 is not included.

random.randrange(stop_num) returns an integer in the range of 0 and stop_num, with stop_num being an integer.

random.randrange(start_num, stop_num, step) it returns a random integer from the range start_num to stop_num, but only counting in steps. For example. if start_num is 100 and stop_num is 120 and the step is 3, the random integer returned would be chosen from the integers (100, 103, 106, 109, 112, 115, 118)

Random Numbers

Order of operations

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.