Appendices

Appendix A

Error Messages and What They Mean

Page 435 of the printed book · 3 sections

Python’s error messages look scary at first, but they follow a pattern. The last line names the kind of error and gives a short reason. The lines above it say where it happened: the file, the line number, and the line itself. Read from the bottom up.

Output
Traceback (most recent call last):
  File "C:\Users\Sara\totals.py", line 4, in <module>
    average = total / count
              ~~~~~~^~~~~~~
ZeroDivisionError: division by zero

Here the last line says what went wrong (dividing by zero), and the line above it says where (line 4 of totals.py). That’s usually all you need. Chapter 8 explains tracebacks in detail, and Chapter 21 shows how to hunt down the harder bugs.

#Errors in your code

These are the errors you’ll meet most often while you’re writing programs. They’re listed alphabetically, so you can find yours quickly.

ErrorWhat it usually meansWhat to tryMore in
AttributeErrorYou asked an object for something it doesn’t have, such as name.uper()Check the spelling. Use dir(thing) to list what it does have. In a class, check __init__ creates the attribute.Ch. 11
FileNotFoundErrorThe file isn’t where Python lookedCheck the name and extension. Build the path from Path(__file__).parent. Open the project folder in VS Code.Ch. 9
ImportErrorThe module exists, but not the name you asked for from itCheck the spelling after from ... import. Don’t name your own file after a module, such as random.py.Ch. 10
IndentationErrorThe spaces at the start of a line don’t line upIndent the block under if, for, def or class by four spaces, and be consistent.Ch. 4
IndexErrorYou asked for a list position that doesn’t existRemember counting starts at 0, and the last item is items[-1] or items[len(items) - 1].Ch. 6
JSONDecodeErrorThe text you tried to read as JSON isn’t valid JSONPrint the text first. Look for single quotes, a trailing comma, or an error page instead of data.Ch. 20
KeyboardInterruptYou pressed Ctrl+C. Not really an errorUseful for stopping a loop that never ends.Ch. 5
KeyErrorThe dictionary has no such keyCheck the spelling and capitals. Use .get(key) when a key might be missing.Ch. 6
ModuleNotFoundErrorPython can’t find a module, often a package you haven’t installedpython -m pip install the package, in the same Python (and virtual environment) that runs your code.Ch. 10, 23
NameErrorYou used a name Python hasn’t seen yetCheck the spelling. Make sure the variable is created before the line that uses it. Did you forget quotes around text?Ch. 3, 8
PermissionErrorThe operating system won’t let Python touch that fileClose the file in Excel or Word, or choose a folder you own.Ch. 14
SyntaxErrorThe line isn’t valid PythonLook for a missing colon, bracket or quote, on that line or the one above it.Ch. 2, 4
TypeErrorThe operation doesn’t work with these types, like "5" + 3Convert with int(), float() or str(). Check you’re passing the right number of arguments.Ch. 3, 7
UnboundLocalErrorInside a function, you changed a variable that lives outside itPass the value in as a parameter and return the new value.Ch. 7
UnicodeDecodeErrorThe file’s characters aren’t in the encoding Python expectedOpen it with encoding="utf-8", or try encoding="utf-8-sig" or "latin-1".Ch. 9, 21
ValueErrorRight type, unusable value, like int("hello ")Check input before converting, or catch it with try and except.Ch. 3, 8
ZeroDivisionErrorYou divided by zero, often an average of an empty listCheck the count isn’t zero first.Ch. 8

#Errors from classes and functions

A few TypeError messages are so common they deserve their own row:

You seeIt meansFix
takes 0 positional arguments but 1 was givenA method is missing selfdef volume_up(self):
missing 1 required positional argumentYou called a function or made an object without all the values it needsCount the parameters in the def line and pass that many
'NoneType' object is not subscriptable (or has no attribute)A function returned nothing, so you got NoneCheck the function ends with return
'str' object is not callableYou used a function’s name as a variable, such as input = 5Rename the variable and restart
unsupported operand type(s) for +: 'int' and 'str'You tried to add a number and textConvert one of them first

#Errors from your computer, not your code

Some messages come from your terminal, your operating system or the internet. Your code may be perfectly fine.

You seeWhat’s going onWhat to do
'python' is not recognized as an internal or external command (Windows)Python isn’t on the PATHTry py. Then see Appendix C.
command not found: python (Mac)On a Mac the command is python3Type python3 instead.
can't open file ... No such file or directoryThe terminal isn’t in the folder where your file isUse cd to go to the folder, or run it with VS Code’s Run button.
error: externally-managed-environmentYour system’s Python doesn’t want packages installed into itMake a virtual environment first (Chapter 23).
running scripts is disabled on this system (PowerShell)A Windows security setting blocks the activate scriptUse Command Prompt, or see Appendix C.
CERTIFICATE_VERIFY_FAILEDPython can’t check a website’s security certificateOn a Mac, run Install Certificates.command (Chapter 2).
ConnectionError or Max retries exceededNo internet, a typo in the address, or the site is downCheck the address in a browser. Try again later.
Address already in useAnother program, often an old copy of your Flask app, is using that portStop the old one with Ctrl+C, or close the terminal it’s in.
SMTPAuthenticationErrorThe email server rejected your username or passwordFor Gmail, use an app password (Chapter 27).