Loading lessons...
Cheatsheet: Keywords and Exceptions
Cheatsheet: Keywords and Exceptions
The reserved words and common error types of Python.
A taste of the keywords
and, or, not, if, elif, else, for, while, break, continue, def, return, class, import, from, as, try, except, finally, raise, with, pass, lambda, yield, global, nonlocal, True, False, None.
You cannot use these as variable names.
Common exceptions
| Exception | Trigger |
|---|---|
NameError | Unknown name |
TypeError | Wrong type |
ValueError | Wrong value |
IndexError | Index out of range |
KeyError | Missing dict key |
ZeroDivisionError | Division by zero |
FileNotFoundError | Missing file |
AttributeError | Missing attribute/method |
ImportError | Import failed |
SyntaxError | Bad syntax |
IndentationError | Bad indentation |
The exception hierarchy
All exceptions inherit from BaseException. Most come from Exception. Catch specific types before the general one.
try:
risky()
except ValueError:
print("Bad value")
except Exception:
print("Something else")
TL;DR
- Keywords are reserved words you can't use as names.
- Each exception type signals a specific problem.
- Catch specific exceptions first, general ones last.
- Everything except BaseException's siblings inherits from Exception.