Lesson 101 +10 XP

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

ExceptionTrigger
NameErrorUnknown name
TypeErrorWrong type
ValueErrorWrong value
IndexErrorIndex out of range
KeyErrorMissing dict key
ZeroDivisionErrorDivision by zero
FileNotFoundErrorMissing file
AttributeErrorMissing attribute/method
ImportErrorImport failed
SyntaxErrorBad syntax
IndentationErrorBad 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.