Kahibaro
Discord Login Register

Common errors and solutions

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:

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

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

1.2 `IndentationError`

Common messages:

What it means
Your spaces (indentation) don’t match what Python expects.

Typical causes

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

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

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

Example

my-variable = 5

Fix:

my_variable = 5

2. 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

Examples

Variable used before assignment:

print(age)
age = 10

Fix:

age = 10
print(age)

Typo:

user_name = "Sam"
print(username)

Fix:

user_name = "Sam"
print(user_name)

How to fix / avoid

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

Example

count = 0
def increment():
    count = count + 1
    print(count)
increment()

Error:

UnboundLocalError: local variable 'count' referenced before assignment

Fix 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

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)   # 30

3.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

Example

age_text = "twenty"
age = int(age_text)

Fix:

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

value = int("123")[0]   # trying to index the result of int()

Example

number = 123
print(number[0])

Fix:

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

Fix

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

Example

numbers = [10, 20, 30]
print(numbers[3])

Indexes valid here: 0, 1, 2. Index 3 is out of range.

Fix:

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

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 append

Fix:

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

Example

import maths

Fix (correct name):

import math

If an external library: install it with pip (in a terminal):

:::bash
pip install requests

Then in Python:

import requests

7.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

Example

from math import squareroot

Fix:

from math import sqrt

8. 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

Example

file = open("data.txt")

If data.txt is not in the same directory, you’ll get this error.

Fix

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

Fix

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

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 happens

Correct:

greet()

Or when assigning:

result = input   # result is now the input function, not user input

Correct:

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:

  1. Last line: the actual error type and message
    • ZeroDivisionError: division by zero
  2. Lines above: where the error came from
    • divide(10, 0) in main code
    • return a / b inside divide

When debugging:

11. Quick Checklist for Fixing Errors

When you see an error:

  1. Read the error type (e.g., NameError, TypeError).
  2. Read the message carefully; it often tells you exactly what’s wrong.
  3. Go to the line number mentioned (and sometimes the line before).
  4. Check for:
    • Typos
    • Missing :, (), [], {}
    • Wrong indentation
    • Misused = vs ==
    • Wrong types (string vs number)
  5. 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.

Views: 16

Comments

Please login to add a comment.

Don't have an account? Register now!