Import Statements
Python has various built-in functions, that include print()
, input()
, len()
and a lot other ones. Another exciting thing about Python are the set of modules they provide, called the standard library. Each module is a Python program that contains a related group of functions that can be embedded in your programs. For example, the math
module has mathematics-related functions, the random
module has random number–related functions, and so on.
To use the functions from a module, we need to learn how to use the import
function. In code, an import
function includes:
- The
import
keyword - The name of the module
- More module names (optional), which are seperated by commas
Example:
import random
for i in range(0,10):
print(random.randint(1,10))
This function prints random integers between 1,10 (excluding 10) ten times. randint()
is a function provided by the random
module and can be used in the way we just showed.
The result would be:
10
2
2
4
8
9
10
5
7
1
NOTE: When you type the same program in the console, it will give a different output as different random numbers will be generated.
An alternative form of the import
statement is composed of the from
keyword, followed by the module name, the import
keyword, and a star; for example, from random import *
. This imports all the functions of the random
module.