A module is a Python file whose code you can use.
Instead of writing every useful feature yourself, you can import a module that already contains it. For now, we will use modules from Python’s standard library: helpful code that comes with Python.
import math
print(math.sqrt(25))import math makes the math module available. sqrt is a function inside that module, so math.sqrt(25) calls that particular function.
5.0The dot helps Python—and a reader of your code—see where sqrt comes from. The standard library has many other modules, so later you will not need to reinvent every tool you use.
A useful random example: random.randint(1, 10) returns a whole random number from 1 through 10. The two limits are both included, so a different run can print a different number.
import random
broj = random.randint(1, 10)
print(broj)random is another standard-library module. Run this more than once to see that the result can change.
import math
print(math.sqrt(16))
from math import sqrt
print(sqrt(16))
import math as m
print(m.sqrt(16))The first form keeps the module name. The second imports only sqrt, so it can be called directly. The third gives math the shorter alias m; an alias is optional, not something you must always use.
from math import * # Usually avoid thisThis imports many names at once, which can make it unclear where a name came from. Prefer a clear module name or import the one function you need.
Read an import step by step
- 1. Import the moduleWrite
import mathbefore using code from math. - 2. Name the moduleWrite
math.to say which module you are using. - 3. Call a functionWrite the function name and its parentheses, such as
math.sqrt(25). - 4. Reuse helpful codePython’s standard library offers modules now; later, you can make your own modules too.
Common mistakes
- Forgetting the importPython must see import math before you use math.sqrt(...).
- Forgetting the module nameAfter import math, write math.sqrt(...), not just sqrt(...).
- Mixing import stylesAfter from math import sqrt, call sqrt(...). After import math as m, call m.sqrt(...).
- Assuming random always gives a new visible resultA random result can repeat by chance, even though Python chooses it again each run.
