Chapter 6 Built-In Functions
Chapter 6 Built-In Functions
❮ PreviousNext ❯
Python has a set of built-in math functions, including an extensive math
module, that allows you to perform mathematical tasks on numbers.
Example
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
Write down the output:
Try it Yourself »
The abs() function returns the absolute (positive) value of the specified number:
Example
x = abs(-7.25)
print(x)
Write down the output:
Try it Yourself »
Example
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):
x = pow(4, 3)
print(x)
Try it Yourself »
When you have imported the math module, you can start using methods and
constants of the module.
The math.sqrt() method for example, returns the square root of a number:
Example
import math
x = math.sqrt(64)
print(x)
Write down the output:
Try it Yourself »
The math.trunc() method for example, returns the truncated integer parts of a
number:
Example
import math
x = math.trunc(12.6)
print(x)
Write down the output:
The math.ceil() method rounds a number upwards to its nearest integer, and the
math.floor() method rounds a number downwards to its nearest integer, and
returns the result:
Example
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
Try it Yourself »
Example
import math
x = math.pi
print(x)
Write down the output:
Practice:
Convert each of the following expressions into a Python statement:
1. Write a program that calculates the total surface area of a circular cone.
2. Write a function that calculate the area of a triangle by the length of its
three sides, namely a, b and c. The formula for the area A is
Then write a program to use the function to calculate the area of a triangle, as