Functions
Modules
Import a module and call its functions.
A module is a Python file (.py) containing related function definitions. To use one, import it, then call its functions as modulename.functionname(): import math, then math.sqrt(25) gives 5.0. Module names are written in small letters.
Useful functions in the math module:
- ceil(x) rounds up to the next whole number: ceil(4.2) is 5, and ceil(-2.3) is -2.
- floor(x) rounds down: floor(-2.3) is -3.
- fabs(-7) is 7.0 (absolute value, as a float); factorial(4) is 24; gcd(12, 18) is 6.
- fmod(x, y) gives the remainder, with the sign of x.
- pow(x, y) gives a float; sqrt(x) the square root.
- sin(x), cos(x) and the other trigonometric functions take x in radians.
The random module: random() gives a float from 0.0 up to (but not including) 1.0; randint(x, y) gives a whole number from x to y, both included (randint(1, 6) acts like a dice); randrange(y) gives one from 0 to y - 1, and randrange(x, y) from x to y - 1.
The statistics module: mean(), median() and mode(). For example, statistics.median([3, 9, 5]) is 5 (the middle value once sorted).
Instead of importing a whole module, you can import only some of its functions: from math import ceil, sqrt. They are then called without the module name: sqrt(16). Using the output of one function as the input of another, as in sqrt(ceil(15.2)), is called composition.
You can make your own module: save your functions in a .py file, such as basic_math.py, with a docstring (a description in triple quotes) at the top. Then import basic_math and call basic_math.addnum(2, 5). print(basic_math.__doc__) shows the docstring.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.