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.
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.
| Error | What it usually means | What to try | More in |
|---|---|---|---|
AttributeError | You 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 |
FileNotFoundError | The file isn’t where Python looked | Check the name and extension. Build the path from Path(__file__).parent. Open the project folder in VS Code. | Ch. 9 |
ImportError | The module exists, but not the name you asked for from it | Check the spelling after from ... import. Don’t name your own file after a module, such as random.py. | Ch. 10 |
IndentationError | The spaces at the start of a line don’t line up | Indent the block under if, for, def or class by four spaces, and be consistent. | Ch. 4 |
IndexError | You asked for a list position that doesn’t exist | Remember counting starts at 0, and the last item is items[-1] or items[len(items) - 1]. | Ch. 6 |
JSONDecodeError | The text you tried to read as JSON isn’t valid JSON | Print the text first. Look for single quotes, a trailing comma, or an error page instead of data. | Ch. 20 |
KeyboardInterrupt | You pressed Ctrl+C. Not really an error | Useful for stopping a loop that never ends. | Ch. 5 |
KeyError | The dictionary has no such key | Check the spelling and capitals. Use .get(key) when a key might be missing. | Ch. 6 |
ModuleNotFoundError | Python can’t find a module, often a package you haven’t installed | python -m pip install the package, in the same Python (and virtual environment) that runs your code. | Ch. 10, 23 |
NameError | You used a name Python hasn’t seen yet | Check the spelling. Make sure the variable is created before the line that uses it. Did you forget quotes around text? | Ch. 3, 8 |
PermissionError | The operating system won’t let Python touch that file | Close the file in Excel or Word, or choose a folder you own. | Ch. 14 |
SyntaxError | The line isn’t valid Python | Look for a missing colon, bracket or quote, on that line or the one above it. | Ch. 2, 4 |
TypeError | The operation doesn’t work with these types, like "5" + 3 | Convert with int(), float() or str(). Check you’re passing the right number of arguments. | Ch. 3, 7 |
UnboundLocalError | Inside a function, you changed a variable that lives outside it | Pass the value in as a parameter and return the new value. | Ch. 7 |
UnicodeDecodeError | The file’s characters aren’t in the encoding Python expected | Open it with encoding="utf-8", or try encoding="utf-8-sig" or "latin-1". | Ch. 9, 21 |
ValueError | Right type, unusable value, like int("hello ") | Check input before converting, or catch it with try and except. | Ch. 3, 8 |
ZeroDivisionError | You divided by zero, often an average of an empty list | Check 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 see | It means | Fix |
|---|---|---|
takes 0 positional arguments but 1 was given | A method is missing self | def volume_up(self): |
missing 1 required positional argument | You called a function or made an object without all the values it needs | Count 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 None | Check the function ends with return |
'str' object is not callable | You used a function’s name as a variable, such as input = 5 | Rename the variable and restart |
unsupported operand type(s) for +: 'int' and 'str' | You tried to add a number and text | Convert 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 see | What’s going on | What to do |
|---|---|---|
'python' is not recognized as an internal or external command (Windows) | Python isn’t on the PATH | Try py. Then see Appendix C. |
command not found: python (Mac) | On a Mac the command is python3 | Type python3 instead. |
can't open file ... No such file or directory | The terminal isn’t in the folder where your file is | Use cd to go to the folder, or run it with VS Code’s Run button. |
error: externally-managed-environment | Your system’s Python doesn’t want packages installed into it | Make a virtual environment first (Chapter 23). |
running scripts is disabled on this system (PowerShell) | A Windows security setting blocks the activate script | Use Command Prompt, or see Appendix C. |
CERTIFICATE_VERIFY_FAILED | Python can’t check a website’s security certificate | On a Mac, run Install Certificates.command (Chapter 2). |
ConnectionError or Max retries exceeded | No internet, a typo in the address, or the site is down | Check the address in a browser. Try again later. |
Address already in use | Another program, often an old copy of your Flask app, is using that port | Stop the old one with Ctrl+C, or close the terminal it’s in. |
SMTPAuthenticationError | The email server rejected your username or password | For Gmail, use an app password (Chapter 27). |