Importing names with from
Writing math. in front of every name gets long when a program uses the same function many times. The from form of import brings chosen names from a module straight into your program:
from math import sqrt
print(sqrt(81))
print(sqrt(2))
9.0
1.4142135623730951Now sqrt works on its own, without the prefix. To bring in several names, separate them with commas:
from math import floor, ceil, pi
print(floor(pi))
print(ceil(pi))
print(f"{pi:.2f}")
3
4
3.14Only what you import
from math import sqrt brings in sqrt and nothing else. The name math itself isn't defined, so math.sqrt fails, and so does any other name of the module that you didn't list:
from math import sqrt
print(sqrt(25))
print(math.sqrt(36))
5.0Traceback (most recent call last):
File "main.py", line 4, in <module>
print(math.sqrt(36))
^^^^
NameError: name 'math' is not defined. Did you forget to import 'math'?Python's guess is one way to fix it: add import math. The other is to write sqrt(36), the name you did import.
Which form to use
Both forms reach the same functions, so choose by what reads best:
import mathkeeps the module's name in every call.math.floor(x)tells the reader exactly wherefloorcomes from.from math import flooris shorter, which is handy when a program uses a function often.
There's a third form, from math import *, which imports every name the module has. It saves typing, but it hides where the names come from, and it can quietly replace a name of your own. The math module has a value called e (2.718...), so it overwrites a variable e of yours:
e = "Eve"
from math import *
print(e)
2.718281828459045No error, just a wrong value. Use the star form only for quick experiments, if at all.