L3·Functions & Modules

📦Modules & Imports

Organizing code across files.

importfrompackage__init__

§ 1Import forms

import math, from math import sqrt, from math import sqrt as s, import math as m.

§ 2Packages

A directory with __init__.py (optional in 3.3+) is a package. Sub-modules via dotted paths.

§ 3__name__ == '__main__'

Idiomatic guard: code inside runs only when the module is executed directly, not on import.

Example

1import math
2from math import pi, sqrt
3
4print(math.tau)
5print(sqrt(pi))
6
7if __name__ == '__main__':
8 print('run directly')

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
Which imports sqrt directly?