Skip to main content

Loading commands from the library in python

Loading commands from the library in python





Python has a very extensive library of commands, documented in the Python Library Reference
Manual [2]. These commands are organized into modules. One of the available modules is especially
useful for us: the math module. Let’s see how it may be used.
>>> from math import sqrt , exp
>>> exp ( -1)
0.36787944117144233
>>> sqrt (2)
1.4142135623730951
We first import
√ the sqrt and exp functions from the math module, then use them to compute
−1
e = 1/e and 2.
Once we have loaded a function from a module, it is available for the rest of that session. When
we start a new session, we have to reload the function if we need it.
Note that we could have loaded both functions sqrt and exp by using a wildcard *:
>>> from math import *
which tells Python to import all the functions in the math module.
What would have happened if we forgot to import a needed function? After starting a new session,
if we type
>>> sqrt (2)
T r a c e b a c k ( most recent call last ):
File " < stdin > " , line 1 , in < module >
N a m e E r r o r : name ’ sqrt ’ is not d e f i n e dwe see an example of an error message, telling us that Python does not recognize sqrt.


Comments