xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Modules and imports

Functions and modules5 min readLesson 3 of 3

A file is a module. Importing it runs the file once and binds its names.

python
import math
math.sqrt(16)          # 4.0

from math import sqrt  # bring one name in
sqrt(16)

import numpy as np     # an alias, the usual convention

Everything in the standard library is already installed. A short list worth knowing:

python
import json, re, pathlib, datetime, statistics, itertools

Keep imports at the top of the file, grouped: standard library, third-party, then local. That order makes a missing dependency obvious.

A module runs its top-level code on import. Guard the part that should only run from the command line:

python
def main():
    ...

if __name__ == "__main__":
    main()