Python comes with a large number of in-built functions. These are saved in modules. To use the codes in Python modules, we have to import them into our programs first. We do that by using the import keyword. There are three ways to do it.
The first way is to import the entire module by typing import moduleName.
For example, to import the random module, we write import random. To use the randrange() function in the random module we type random.randrange(1, 10).
If it seems troubling to to type the entire module name the entire time, we can import it by typing import random as r (where r is any name of our choice). Now, to use the randrange() function, we can simply type r.randrange(1, 10).
The third way is to import specific functions from the module by typing moduleName import name1[, name2[, ... nameN]].
For example, to import the randrange() function from the random module, we write from random import randrange. If we want to import more than one, we separate them with a comma. To import the randrange() and randint() functions, we type from random import randrange, randint. To use the function now, we do not have to use the dot notation anymore. We can simply type randrange(1, 10).
No comments:
Post a Comment