Table of Contents
How to Use This Appendix
This appendix lists common Python errors beginners run into and how to fix them.
Each entry has:
- Error message (or type)
- What it means (in plain language)
- Typical causes
- How to fix / avoid it
- Short examples
You do not have to memorize everything here. Use this as a lookup table: when you see an error, come back and search for its name or a part of the message.
1. Syntax Errors
A SyntaxError means: “Python cannot understand this line at all.”
It’s usually caused by a missing symbol, extra symbol, or something written in the wrong order.
1.1 `SyntaxError: invalid syntax`
What it means
Python found something that doesn’t follow the rules of the language.
Typical causes
- Missing
:afterif,elif,else,for,while,def,class - Using
=instead of==in a condition - Unclosed parentheses, brackets, or quotes
- Random characters or typos
Examples
Missing colon:
if x > 10
print("Too big")Fix:
if x > 10:
print("Too big")
Using = in an if:
if x = 5:
print("x is five")Fix:
if x == 5:
print("x is five")Unclosed string:
message = "Hello
print(message)Fix:
message = "Hello"
print(message)How to fix / avoid
- Look at the line number and one line above (sometimes the error is there).
- Check for:
- Missing
: - Unclosed
()/[]/{}/ quotes - Using
=instead of==in conditions
1.2 `IndentationError`
Common messages:
IndentationError: unexpected indentIndentationError: expected an indented blockIndentationError: unindent does not match any outer indentation level
What it means
Your spaces (indentation) don’t match what Python expects.
Typical causes
- Forgetting to indent code inside an
if,for,while,def, etc. - Mixing tabs and spaces
- Indenting too much or too little compared to previous lines
Examples
Expected an indented block:
if x > 10:
print("Too big")Fix:
if x > 10:
print("Too big")Unexpected indent:
x = 10
print(x)Fix:
x = 10
print(x)How to fix / avoid
- Use 4 spaces per indentation level (most editors handle this automatically).
- Don’t mix tabs and spaces; configure your editor to insert spaces when you press Tab.
- Make sure blocks under
if,for,while,def, etc. are consistently indented.
1.3 `SyntaxError: EOL while scanning string literal`
What it means
Your string started, but it didn’t end before the end of the line (EOL = end of line).
Typical causes
- Missing closing quote on a string
- Using mismatched quotes (
"something')
Example
name = "Alice
print(name)Fix:
name = "Alice"
print(name)Mismatched quotes:
message = "It's a nice day"This is valid, but this is not:
message = "It's a nice day'Fix (make quotes match):
message = "It's a nice day"
# or
message = 'It\'s a nice day'1.4 `SyntaxError: invalid character in identifier`
What it means
You used a character that can’t be part of a variable/function name.
Typical causes
- Copy–pasting code from the web that has “fancy” quotes or invisible characters
- Using
-or spaces in variable names (my-variable,my variable) - Using non-Latin characters in names (in beginner code, usually accidental)
Example
my-variable = 5Fix:
my_variable = 52. Name and Variable Errors
2.1 `NameError: name 'x' is not defined`
What it means
You tried to use a name (variable, function, etc.) that Python doesn’t know about.
Typical causes
- Typo in the name
- Using a variable before assigning to it
- Variable defined inside a block but used outside incorrectly
- Forgetting to call a function that defines something before using it
Examples
Variable used before assignment:
print(age)
age = 10Fix:
age = 10
print(age)Typo:
user_name = "Sam"
print(username)Fix:
user_name = "Sam"
print(user_name)How to fix / avoid
- Double-check spelling and letter case (
Namevsname). - Make sure variables are assigned before they’re used.
- Keep variable names simple and consistent.
2.2 `UnboundLocalError: local variable 'x' referenced before assignment`
What it means
Inside a function, you tried to use a variable before assigning a value to it in that function.
Typical causes
- Modifying a variable inside a function that also exists outside, without using
global(or better: passing it as a parameter).
Example
count = 0
def increment():
count = count + 1
print(count)
increment()Error:
UnboundLocalError: local variable 'count' referenced before assignmentFix by passing as argument and returning:
count = 0
def increment(value):
value = value + 1
print(value)
return value
count = increment(count)3. Type Errors and Conversion Problems
3.1 `TypeError: can only concatenate str (not "int") to str`
What it means
You tried to “add” a number to a string using +.
Typical causes
- Combining text and numbers without converting the number to
str - Using user input (which is a string) and adding it to a number
Example
age = 25
print("You are " + age + " years old")Fix:
age = 25
print("You are " + str(age) + " years old")Or use f-strings:
age = 25
print(f"You are {age} years old")3.2 `TypeError: unsupported operand type(s) for +: 'int' and 'str'`
Similar to above, but the error shows up when you try to use + between a string and a number in any context.
Example
x = 10
y = "20"
result = x + y
Fix: convert y to a number or x to string, depending on what you really want:
# If you want numeric addition
x = 10
y = "20"
result = x + int(y) # 303.3 `ValueError: invalid literal for int() with base 10: '...'`
What it means
You tried to convert a string to an integer, but the string isn’t a proper number.
Typical causes
- Calling
int()on input that contains letters or symbols (like"abc"or"12.5") - User pressing Enter without typing anything, giving an empty string
""
Example
age_text = "twenty"
age = int(age_text)Fix:
- Ensure the string only contains digits (for simple cases).
- If it has a decimal point, use
float()instead ofint().
price = "12.5"
value = float(price)3.4 `TypeError: 'int' object is not subscriptable`
What it means
You tried to use indexing ([...]) on something that’s just a number.
Typical causes
- Mistakenly thinking a number is a list, string, or similar
- Forgetting parentheses:
value = int("123")[0] # trying to index the result of int()Example
number = 123
print(number[0])Fix:
- Convert to string if you really want to treat it like text:
number = 123
print(str(number)[0]) # '1'Or use math to extract digits if needed.
4. Input Problems
4.1 Forgetting to convert input to numbers
You won’t always get an error message that says “forgot to convert.” Instead, you might get unexpected behavior or a TypeError.
Example
x = input("Enter a number: ")
y = input("Enter another number: ")
print("Sum:", x + y)
If you enter 2 and 3, you see:
:::text
Sum: 23
Because x and y are strings, + concatenates them.
Fix
Convert to int or float:
x = int(input("Enter a number: "))
y = int(input("Enter another number: "))
print("Sum:", x + y)4.2 `EOFError: EOF when reading a line`
What it means
Python expected input (e.g., from input()), but none was provided.
Typical causes
- Using
input()in environments that don’t support user input (e.g. some online runners) - Program ended or input stream closed unexpectedly
Fix
- If you’re using an environment that doesn’t support input, run the script in a terminal/IDE that does.
- For advanced use, you can wrap
input()intry/except, but for beginners this usually indicates a problem with how the script is being run.
5. Index and Length Errors
5.1 `IndexError: list index out of range`
What it means
You tried to access a list position that does not exist.
Typical causes
- Using an index that’s too large or negative beyond the list length
- Off-by-one errors in loops
- Assuming the list always has a certain number of items
Example
numbers = [10, 20, 30]
print(numbers[3])
Indexes valid here: 0, 1, 2. Index 3 is out of range.
Fix:
- Use a correct index.
- Or loop directly over elements:
for num in numbers:
print(num)Loop off-by-one:
numbers = [10, 20, 30]
for i in range(0, len(numbers)):
print(numbers[i+1])
When i = len(numbers) - 1, i+1 is out of range.
Fix:
for i in range(len(numbers)):
print(numbers[i])5.2 `IndexError: string index out of range`
Same idea as with lists, but with strings.
Example
name = "Bob"
print(name[3])
Indexes valid: 0, 1, 2.
Fix: ensure index is within 0 to len(name) - 1.
6. Attribute and Method Errors
6.1 `AttributeError: 'list' object has no attribute 'X'`
What it means
You tried to use a method or attribute that doesn’t exist on that type.
Typical causes
- Using the wrong method name
- Using string methods on lists or vice versa
- Typo in method name (
appenndinstead ofappend)
Examples
Wrong method on list:
numbers = [1, 2, 3]
numbers.upper()
Fix: use list methods like append, pop, etc.
Typo:
numbers = [1, 2, 3]
numbers.apend(4)Fix:
numbers.append(4)6.2 Using methods on the wrong type
This may show as an AttributeError or other unexpected behavior.
Example
name = "alice"
name.append("!") # strings don't have appendFix:
- For strings, use
+or string methods (upper,lower,replace,strip). - For lists, use
append,extend, etc.
7. Import and Module Errors
7.1 `ModuleNotFoundError: No module named '...'`
What it means
Python cannot find the module you’re trying to import.
Typical causes
- Typo in module name
- Module not installed
- Using the wrong Python environment
Example
import mathsFix (correct name):
import math
If an external library: install it with pip (in a terminal):
:::bash
pip install requests
Then in Python:
import requests7.2 `ImportError: cannot import name 'X' from 'Y'`
What it means
The module Y exists, but it does not contain an object named X.
Typical causes
- Typo in the name of what you’re importing
- Importing something that does not exist in that module
Example
from math import squarerootFix:
from math import sqrt8. File and Path Errors
8.1 `FileNotFoundError: [Errno 2] No such file or directory: '...'`
What it means
Python tried to open a file, but it couldn’t find it at the given path.
Typical causes
- Incorrect file name or path
- File is in a different folder than your script
- Using relative paths incorrectly
Example
file = open("data.txt")
If data.txt is not in the same directory, you’ll get this error.
Fix
- Check the exact file name (including case).
- Make sure the file is in the correct directory.
- Use a full path or a correct relative path:
file = open("data/data.txt")8.2 `PermissionError: [Errno 13] Permission denied: '...'`
What it means
You don’t have permission to read or write the file at that path.
Typical causes
- Trying to write to a protected system folder
- Trying to open a file in write mode where you don’t have write permissions
Fix
- Choose a location where you have permission (e.g., your user folder).
- Change file mode if appropriate (read vs write).
- On some systems, you might need administrator rights (outside this course’s scope).
9. Logical and Common Beginner Mistakes (No Error Message, Wrong Result)
Sometimes your code runs without errors but gives the wrong answer. These are logic errors.
9.1 Using `=` instead of `==` in conditions
Modern Python gives a SyntaxError if you do this directly in a condition, but it’s still conceptually important.
Wrong idea
“= checks if two values are equal.”
In Python, = assigns a value; == compares values.
Example
x = 5
if x = 5: # invalid syntax in Python
print("x is five")Correct:
x = 5
if x == 5:
print("x is five")9.2 Off-by-one errors in loops
Typical causes
- Confusion about
range(start, stop)wherestopis not included - Mixing up indexes and counts
Example
You want to loop 5 times:
for i in range(1, 5):
print(i)
This prints 1, 2, 3, 4, not 5.
Correct for 1 to 5:
for i in range(1, 6):
print(i)Correct for 0 to 4:
for i in range(5): # same as range(0, 5)
print(i)9.3 Using `if x == True` instead of just `if x`
This is not an error, but it’s unnecessary and can lead to confusion.
Example
is_logged_in = True
if is_logged_in == True:
print("Welcome")More Pythonic:
if is_logged_in:
print("Welcome")
For False:
if not is_logged_in:
print("Please log in")9.4 Forgetting `()` when calling a function
What happens
You pass the function itself instead of its result, or you never actually call it.
Example
def greet():
print("Hello")
greet # nothing happensCorrect:
greet()Or when assigning:
result = input # result is now the input function, not user inputCorrect:
result = input("Your name: ")9.5 Using `return` vs `print`
Confusing print() (which shows something on the screen) with return (which gives a value back from a function) is very common.
Example
def add(a, b):
print(a + b)
result = add(2, 3)
print("Result is:", result)This prints:
:::text
5
Result is: None
Because add doesn’t return anything.
Correct:
def add(a, b):
return a + b
result = add(2, 3)
print("Result is:", result)10. Working With Tracebacks (Error Messages)
When an error occurs, Python prints a traceback: a stack of lines showing where the error happened.
Example:
def divide(a, b):
return a / b
result = divide(10, 0)Traceback (simplified):
:::text
Traceback (most recent call last):
File "example.py", line 4, in <module>
result = divide(10, 0)
File "example.py", line 2, in divide
return a / b
ZeroDivisionError: division by zero
How to read:
- Last line: the actual error type and message
ZeroDivisionError: division by zero- Lines above: where the error came from
divide(10, 0)in main codereturn a / binsidedivide
When debugging:
- Start from the bottom line (error name and message).
- Then look at your code lines mentioned above it.
11. Quick Checklist for Fixing Errors
When you see an error:
- Read the error type (e.g.,
NameError,TypeError). - Read the message carefully; it often tells you exactly what’s wrong.
- Go to the line number mentioned (and sometimes the line before).
- Check for:
- Typos
- Missing
:,(),[],{} - Wrong indentation
- Misused
=vs== - Wrong types (string vs number)
- If stuck:
- Try simplifying the code (comment out parts).
- Print intermediate values with
print()to see what’s happening. - Compare with small working examples from earlier chapters.
Use this appendix as a reference anytime you see an error you don’t understand. Over time, you’ll start to recognize these patterns immediately.