Every Python file is a module. When you write import, Python finds that file, runs it once from top to bottom, and stores the names it defined so your file can reach them.
math in its own library first, then in the folder of your program.math.sqrt, math.pi.All five forms load the same file. They differ in which names appear in your file and in how much you write at every call.
| Form | What lands in your file | How you call it |
|---|---|---|
| import math | the module, under its own name | math.sqrt(81) |
| import statistics as st | the module, under a shorter name | st.mean(data) |
| from math import sqrt | one name, on its own | sqrt(81) |
| from math import sqrt, pi | several names, on their own | sqrt(pi) |
| from math import * | every public name in the module | floor(2.7) |
With from math import * you no longer know where a name came from, and a module name can silently replace one of yours. If math defines pow and your file defines pow too, one of them disappears without any message.
The two fragments print the same number. Run them and watch which line the value comes from.
The module is loaded, yet the plain name sqrt was never created in your file, so Python reports a NameError.
The standard library is the set of modules that comes inside the Python installation. No download, no version to choose, no folder to prepare: import and the code is there.
| Module | What it holds | A call you will use |
|---|---|---|
| math | square roots, rounding, constants | math.sqrt(81) |
| random | random numbers and random choices | random.randint(1, 6) |
| statistics | mean, median and mode of a list | statistics.mean(scores) |
| datetime | dates, times and differences between them | datetime.date.today() |
| time | pauses and timestamps | time.sleep(2) |
| os | files, folders and the system around you | os.listdir() |
| json | text into data, data into text | json.loads(text) |
| Question | standard library | third party |
|---|---|---|
| Who wrote it | The Python core team | Anyone, from one person to a company |
| Where it comes from | Inside the installation | The PyPI catalogue, fetched with pip |
| Before importing | Nothing to do | pip install once, per machine |
| On a new computer | Present already | Missing until installed again |
| Version | Tied to your Python version | Chosen by you, and updated separately |
| Examples | math, random, json, datetime | numpy, pandas, requests, matplotlib |
The import line looks identical in both cases. import json and import pandas are written the same way, and the only difference appears on a machine where pandas was never installed.
pip is the installer that comes with Python. It runs in the terminal rather than inside your program, and one install serves every file on that machine.
Importing a package that was never installed raises ModuleNotFoundError: No module named 'pandas'. The line is correct Python, so the error appears while the program runs and not when you save the file. In Colab many packages are installed already, which is why the same file can work there and fail on your own computer.
A syntax error is a sentence Python cannot read, so nothing runs. An exception is a sentence Python read and then could not carry out, so the program runs until that line and stops there.
Only the second kind can be caught. try guards lines that Python already understands, so a missing bracket stays your problem and no amount of error handling repairs it.
Every exception carries a name, and the name tells you what kind of promise the line broke. These are the ones you will produce in this course.
| Name | Raised when | Example |
|---|---|---|
| ValueError | right type, impossible value | int("4x") |
| TypeError | an operation between wrong types | "3" + 5 |
| ZeroDivisionError | a division whose divisor is zero | 10 / 0 |
| IndexError | a position beyond the last one | [1, 2][5] |
| KeyError | a key that the dictionary lacks | {"a": 1}["b"] |
| NameError | a name never assigned | print(total) |
| ModuleNotFoundError | importing a package never installed | import pandas |
When nothing catches an exception, Python prints a traceback and the program ends. Read it from the bottom, where the name and the message are.
try marks lines that might raise. When one of them does, Python abandons the rest of the block and jumps to the except clause whose name matches. The program continues after the whole structure.
A full structure has four parts. Only try and except are required, and the other two exist to keep the guarded block as short as possible.
| Clause | Runs when | Required |
|---|---|---|
| try | always, first | yes |
| except Name | an exception of that name was raised | at least one |
| else | the try block finished with no exception | no |
| finally | always, last, caught or not | no |
Several except clauses may follow one try, and Python tests them in the order you wrote. The first name that matches wins and the others are ignored, so a single run never enters two of them.
Anything you place inside try is guarded, including code that was never in danger. Moving it to else keeps the try block down to the lines that can really fail, and stops the except clause from catching an error you did not mean to hide.
Three values, one program. Pick a value for raw and run it: the highlight follows the lines Python actually executes, and the panel below collects what reaches the screen.
A bare except catches everything, including the mistakes you wrote by accident. Naming the exception keeps your handler for the situation you planned and lets the rest reach you as a traceback.
totl raises NameError, and the message blames the user for an error that belongs to you.Repeating the try structure inside a while loop is the usual way to ask again until the value is usable, and it is the pattern most of your programs will end up using.
Trace each fragment before pressing Check. The answer button is there for when your trace and the verdict disagree.