A brief note on Errors and Modules: the six errors to know and how to read a traceback, try and except, asking again, raising your own errors, and the math, random, statistics and datetime modules. With a worked example, practice, a program and questions to check yourself.
A brief note on Errors and Modules. Read it before a test. Try each question at the end before you open its answer.
| Error | A typical cause |
|---|---|
ValueError | the right type, a wrong value: int("ten") |
ZeroDivisionError | dividing by 0 |
IndexError | a position past the end of a list |
KeyError | a key that is not in the dictionary |
TypeError | the wrong type for the job: "5" + 2 |
NameError | a name that was never made |
SyntaxError is found before the program runs. A logic mistake gives no message at all, only a wrong answer.try. Name the error you expect in except.else runs when there was no error. finally runs every time.except (ValueError, ZeroDivisionError) as error: catches two kinds, and error holds the message.try, and never write a bare except:.while True, then try, except with continue, and break once the answer is good. try checks the type; an if checks the range.raise ValueError("the age must be from 0 to 120") makes an error of your own and stops the function at once.if when a short check exists. Try and catch when the check is hard.import math, then math.sqrt(49). Or from math import sqrt, then sqrt(49).ceil rounds up, floor rounds down, trunc cuts off. sin and cos use radians, so convert with math.radians. math.isclose compares two decimal numbers.randint(a, b) includes both ends. choice picks one item, shuffle mixes the list itself, and sample picks different items. random.seed(n) makes the same numbers come again, for testing.mean, median and mode describe a list of numbers; pstdev gives the spread..days is the number of days. timedelta adds days.dir(math) lists the tools of a module, and help(math.ceil) explains one.ModuleNotFoundError means a wrong module name. AttributeError means a wrong tool name.What does this program show?
Take the three pieces of text one at a time.
int("4") is 4, and share(120, 4) is 30.0. There is no error, so else runs: 4 people get 30.0 rupees each.int("zero") raises a ValueError at once, so share is never called. The except part prints zero is not usable: invalid literal for int() with base 10: 'zero'.int("0") works, but share raises its own ValueError. The same except catches it: 0 is not usable: people must be at least 1.One except caught two different mistakes: Python's own error, and the one the function raised.
A spinner has four colours. The program asks how many spins to make, refuses a bad answer, counts each colour and names the most common one.
except:. It catches every error, even a spelling mistake in your own code, so the real fault hides.try. With ten lines inside, you cannot tell which one failed. Keep only the risky line there.import maths stops with ModuleNotFoundError: No module named 'maths'.math.root(9) stops with AttributeError: module 'math' has no attribute 'root'.sin. math.sin(30) is the sine of 30 radians. Write math.sin(math.radians(30)).random.py. Then import random brings in your file, not the module.int("3.5"), [10, 20][2] and 10 / 0.try has an except, an else and a finally. The lines in try run with no error. Which of the four parts run?try, with a bare except: that prints "Something went wrong". Give two reasons why this is a poor habit.Log in to join the discussion.
Loading…