[ Web Proxy ]
URL:
Viewing: https://www.pythonbyexample.dev/examples/modules [Back]  [Original]

Modules Python By Example Skip to main content Python By ExampleJourneysAbout
All examplesPython docs reference

Modules

Modules

Modules organize code into namespaces and expose reusable definitions.

Importing a module gives access to its namespace. The math. prefix makes it clear where pi came from.

Source

import math

radius = 3
area = math.pi * radius ** 2
print(round(area, 2))

Output

28.27
SYS.PATHcwdsite-packagesstdlibfirst hitmymod.pyAn import walks sys.path entry by entry; the first directory containing the module wins.

A focused from ... import ... brings one definition into the current namespace. This keeps a common operation concise without importing every name.

Source

from statistics import mean

scores = [8, 10, 9]
print(mean(scores))

Output

9

Modules are objects too. Their attributes include metadata such as __name__, which records the module's import name.

Source

print(math.__name__)

Output

math

Imported modules are cached in sys.modules. Later imports reuse the module object instead of executing the file again.

Source

import sys
print("math" in sys.modules)

Output

True

Notes

See also

WarningsImport Aliases

Run the complete example

code:

Expected output

28.27
9
math
True

Execution time appears here after you run the example.

adewale/pythonbyexample Python 3.13 docs Privacy
Web Proxy Viewer  |  New URL  |  Original Page