10 Common Python Errors Beginners Make (And How to Fix Them Fast)
If you’ve ever stared at a screen full of red text and felt completely lost, you’re in good company. Every single Python developer — from complete beginners to senior engineers — has been there. Python is an incredible language, but its strict rules around syntax, indentation, and data types mean that small mistakes can stop your program cold.
The good news? Python’s error messages are actually quite helpful once you know how to read them. And once you understand the common Python errors beginners make, you’ll spend less time being frustrated and more time actually building things.
In this guide, you’ll learn about the 10 most frequent Python errors, why they happen, and exactly how to fix them — with real code examples throughout. Whether you’re working through your first tutorial or debugging your first project, this article is for you.
Why Do Beginners Make So Many Python Errors?
Python is often praised for being beginner-friendly, and it is. But “easy to start” doesn’t mean “impossible to break.” Here’s why new programmers run into errors so often:
- Python uses indentation instead of braces — unlike JavaScript or C++, the structure of your code is literally defined by whitespace. One misplaced space changes everything.
- Python is case-sensitive —
Name,name, andNAMEare three completely different things. - Data types matter at runtime — Python won’t stop you from writing
"hello" + 5, but it will crash when it runs that line. - Variable scope can be confusing — a variable defined inside an
ifblock doesn’t automatically exist outside it. - Most beginners rush — they write 50 lines before running anything, then can’t find the bug.
The mindset shift that helps most? Stop thinking of errors as failures and start treating them as Python telling you exactly where to look.
How to Read a Python Error Message (Before You Panic)
Before diving into specific errors, let’s talk about the most valuable skill you can develop as a beginner: reading a traceback.
What Is a Traceback?
When Python encounters an error, it prints a traceback — a full report of what went wrong and where. Here’s an example:
Traceback (most recent call last):
File "main.py", line 8, in <module>
result = add(5, 0)
File "main.py", line 3, in add
return a / b
ZeroDivisionError: division by zero
Always read the traceback from bottom to top. The last line is the most important — it tells you the error type (ZeroDivisionError) and a short description (division by zero). The lines above show the call stack: where Python was in your code when things went wrong.
The Three Things to Look For
- Error Type — e.g.,
SyntaxError,TypeError,NameError - Line Number — Python tells you exactly which line caused the problem
- The
^Pointer — for syntax errors, this arrow points directly at the problematic character
Once you master reading tracebacks, most bugs go from mysterious to obvious in seconds.
Error #1 — SyntaxError: Invalid Syntax
What Is a SyntaxError?
A SyntaxError is the most fundamental Python error. It means Python couldn’t even understand your code well enough to run it — like handing someone a sentence with the words in the wrong order.
Python checks your code for syntax problems before running a single line. If it finds one, the program stops immediately.
Common Causes
Missing colon after if, for, def, or while:
# ❌ Wrong
if x > 5
print("Greater")
# ✅ Correct
if x > 5:
print("Greater")
Using print without parentheses (a Python 2 habit):
# ❌ Wrong
print "Hello, World!"
# ✅ Correct
print("Hello, World!")
Unclosed parentheses or brackets:
# ❌ Wrong
result = (10 + 5
print(result)
# ✅ Correct
result = (10 + 5)
print(result)
Using a Python reserved keyword as a variable name:
# ❌ Wrong
class = "Mathematics"
# ✅ Correct
subject = "Mathematics"
How to Fix SyntaxError
- Read the
^pointer — it’s usually pointing right at the problem - Check the line before the one Python highlights — sometimes a missing colon on line 5 causes a reported error on line 6
- Use VS Code or PyCharm, which underline syntax errors in real time before you even run the code
For a complete, step-by-step debugging approach, check out our guide on how to debug Python code step by step.
Error #2 — IndentationError: Expected an Indented Block
What Is an IndentationError?
Python doesn’t use curly braces {} to group code — it uses indentation. That means the number of spaces at the beginning of each line is part of the language itself. An IndentationError occurs when Python finds indentation it didn’t expect, or doesn’t find indentation it required.
IndentationError: expected an indented block after 'if' statement on line 1
Common Causes
No indentation after a block statement:
# ❌ Wrong
def greet():
print("Hello!")
# ✅ Correct
def greet():
print("Hello!")
Mixing tabs and spaces:
# ❌ Wrong — one line uses a tab, another uses spaces
def calculate():
x = 10 # tab
y = 20 # 4 spaces
return x + y
This particular mistake is invisible to the human eye but immediately caught by Python.
Inconsistent indentation inside a block:
# ❌ Wrong
for i in range(5):
print(i)
print("done") # extra spaces = IndentationError
# ✅ Correct
for i in range(5):
print(i)
print("done")
How to Fix IndentationError
- Always use 4 spaces per indentation level — this is the PEP 8 standard
- Never mix tabs and spaces — configure your editor to convert tabs to spaces automatically
- In VS Code: go to Settings → search “Insert Spaces” → enable it, set Tab Size to 4
- Use Black (auto-formatter) — run
pip install blackthenblack yourfile.pyand it will fix indentation automatically
For a thorough walkthrough of this specific error, read our dedicated article: How to Fix IndentationError in Python.
Error #3 — NameError: Name Is Not Defined
What Is a NameError?
Python raises a NameError when you try to use a variable, function, or module that it can’t find in the current scope. This usually means one of three things: you haven’t defined it yet, you spelled it wrong, or it’s out of scope.
NameError: name 'username' is not defined
Common Causes
Using a variable before defining it:
# ❌ Wrong
print(score)
score = 100
# ✅ Correct
score = 100
print(score)
A simple typo in the variable name:
# ❌ Wrong
user_name = "Alice"
print(usernmae) # typo
# ✅ Correct
print(user_name)
Variable defined inside an if block that didn’t run:
# ❌ Risky
if False:
message = "You won!"
print(message) # NameError — message was never assigned
# ✅ Correct — define a default value first
message = "Try again"
if score > 100:
message = "You won!"
print(message)
Forgetting to import a module:
# ❌ Wrong
result = math.sqrt(16) # NameError: name 'math' is not defined
# ✅ Correct
import math
result = math.sqrt(16)
How to Fix NameError
- Define variables before referencing them
- Double-check spelling — Python is case-sensitive, so
Name≠name - Use a linter like Pylint or Flake8 to catch undefined names automatically
- Check your import statements at the top of the file
Proper variable handling starts with understanding input. Learn more in our guide on how to take user input in Python.
Error #4 — TypeError: Unsupported Operand Type
What Is a TypeError?
A TypeError occurs when you try to perform an operation on the wrong type of data. Python is dynamically typed — you don’t declare types upfront — but that doesn’t mean anything goes. You can’t add a number to a string, call len() on an integer, or pass the wrong number of arguments to a function.
TypeError: can only concatenate str (not "int") to str
Common Causes
Mixing strings and numbers:
# ❌ Wrong
age = 25
print("My age is " + age)
# ✅ Correct — convert to string
print("My age is " + str(age))
# ✅ Even better — use an f-string
print(f"My age is {age}")
Calling len() on a number:
# ❌ Wrong
number = 12345
print(len(number)) # TypeError: object of type 'int' has no len()
# ✅ Correct
print(len(str(number))) # Convert to string first
Wrong number of arguments in a function call:
# ❌ Wrong
def add(a, b):
return a + b
result = add(5) # TypeError: add() missing 1 required positional argument
# ✅ Correct
result = add(5, 3)
How to Fix TypeError
- Use explicit conversion functions:
str(),int(),float() - Use f-strings for combining strings with variables — cleaner and safer than concatenation
- Add type hints to your functions for clarity:
def add(a: int, b: int) -> int:
return a + b
- Use
isinstance()to check types before operating on them:
def safe_add(x, y):
if isinstance(x, (int, float)) and isinstance(y, (int, float)):
return x + y
raise TypeError("Both arguments must be numbers")
Error #5 — IndexError: List Index Out of Range
What Is an IndexError?
An IndexError means you tried to access a position in a list, tuple, or string that doesn’t exist. Python uses zero-based indexing, meaning the first item is at index 0, not 1. This catches beginners off guard constantly.
IndexError: list index out of range
Common Causes
Forgetting that indexing starts at zero:
fruits = ["apple", "banana", "cherry"]
# ❌ Wrong
print(fruits[3]) # There is no index 3 — valid indices are 0, 1, 2
# ✅ Correct
print(fruits[2]) # "cherry"
Off-by-one error in a loop:
# ❌ Wrong
scores = [85, 92, 78]
for i in range(len(scores) + 1): # goes one too far
print(scores[i])
# ✅ Correct
for i in range(len(scores)):
print(scores[i])
# ✅ Even better — just iterate directly
for score in scores:
print(score)
Accessing the last element incorrectly:
items = [10, 20, 30]
# ❌ Wrong
print(items[len(items)]) # IndexError
# ✅ Correct
print(items[-1]) # Python's negative indexing — gets last element
print(items[len(items) - 1]) # Also works
How to Fix IndexError
- Always check list length before accessing by index:
if index < len(my_list): - Use negative indexing for the last element:
my_list[-1] - Use a
try-exceptblock when working with user-provided indices:
try:
print(items[index])
except IndexError:
print("That index doesn't exist in the list.")
Practice list operations hands-on by building something fun — check out Build a Guess the Number Game in Python.
Error #6 — ValueError: Invalid Value
What Is a ValueError?
A ValueError is raised when a function receives an argument of the correct type but an inappropriate value. The type is right, but the actual data makes no sense in context.
ValueError: invalid literal for int() with base 10: 'forty-two'
Common Causes
Passing a non-numeric string to int():
# ❌ Wrong
user_input = "forty-two"
number = int(user_input) # ValueError
# ✅ Correct — validate first
user_input = input("Enter a number: ")
try:
number = int(user_input)
print(f"You entered: {number}")
except ValueError:
print("That's not a valid number. Please try again.")
Converting a float string directly to int:
# ❌ Wrong
n = int("3.14") # ValueError
# ✅ Correct
n = int(float("3.14")) # Convert to float first, then int → 3
Unpacking the wrong number of values:
# ❌ Wrong
a, b, c = [1, 2] # ValueError: not enough values to unpack
# ✅ Correct
a, b = [1, 2]
Using max() or min() on an empty list:
# ❌ Wrong
numbers = []
print(max(numbers)) # ValueError: max() arg is an empty sequence
# ✅ Correct
if numbers:
print(max(numbers))
else:
print("The list is empty.")
How to Fix ValueError
- Always wrap user input conversion in
try-except ValueError - Validate data before passing it to functions
- Use
float()as an intermediate step when converting decimal strings toint()
Error #7 — ModuleNotFoundError: No Module Named ‘…’
What Is ModuleNotFoundError?
When you write import requests or import pandas, Python looks through a list of known locations for that module. If it can’t find it, you get a ModuleNotFoundError. This was introduced in Python 3.6 as a more specific version of the older ImportError.
ModuleNotFoundError: No module named 'requests'
Common Causes
The package simply isn’t installed yet:
# You wrote this in your script:
import requests
# But you haven't installed it
# Fix: run this in your terminal:
# pip install requests
Installed in the wrong Python environment:
This is extremely common when you have multiple Python versions or are using virtual environments. You install with pip install, but it goes into a different Python than the one running your code.
# ✅ Always use this instead — it installs into the active interpreter
python -m pip install requests
A typo in the module name:
# ❌ Wrong
import numppy # typo
# ✅ Correct
import numpy
A custom module file can’t be found:
If you have a file called utils.py and you’re running your script from a different directory, Python won’t find it.
# Make sure you're running your script from the right directory
cd /path/to/your/project
python main.py
How to Fix ModuleNotFoundError
- Install the package:
python -m pip install <package-name> - Verify the installation:
pip list | grep <package-name> - Check you’re in the right virtual environment:
which python(Mac/Linux) orwhere python(Windows) - Double-check spelling against the official package name on PyPI
If you’re working with data science tools like pandas and running into import errors during setup, our Pandas Tutorial for Beginners walks through installation and environment setup from scratch.
Error #8 — AttributeError: Object Has No Attribute
What Is an AttributeError?
An AttributeError is raised when you try to use a method or attribute that doesn’t exist on a particular object. Every object in Python has specific methods available — a list has .append(), but it doesn’t have .lower(). Calling the wrong method is a very common beginner mistake.
AttributeError: 'list' object has no attribute 'lower'
Common Causes
Calling a string method on a list:
# ❌ Wrong
tags = ["python", "beginner", "coding"]
print(tags.lower()) # AttributeError — lists don't have .lower()
# ✅ Correct — apply it to each string item
tags_lower = [tag.lower() for tag in tags]
print(tags_lower)
Calling a method on a None return value:
# ❌ Wrong
def get_user():
return None # Function didn't find a user
user = get_user()
print(user.name) # AttributeError: 'NoneType' object has no attribute 'name'
# ✅ Correct
user = get_user()
if user is not None:
print(user.name)
Typo in a method name:
# ❌ Wrong
text = "hello world"
print(text.uper()) # AttributeError — it's .upper(), not .uper()
# ✅ Correct
print(text.upper())
How to Fix AttributeError
- Use
dir(object)in the Python REPL to see all available methods on any object:dir("hello") - Always check for
Nonebefore calling methods on the result of a function - Use
hasattr(obj, 'method_name')to safely check if an attribute exists before using it - Use an IDE — they auto-complete method names and catch typos instantly
Understanding how Python objects and their attributes work comes down to understanding classes. Read our beginner-friendly OOP in Python Explained guide to build that foundation.
Common Logic Errors Beginners Don’t Realize They’re Making
Logic errors are the sneakiest of all — your program runs without crashing, but produces the wrong output. Python can’t catch these for you; you have to find them yourself.
Using = Instead of == in a Condition
# ❌ Wrong — this assigns 10 to x instead of comparing
x = 5
if x = 10: # SyntaxError in Python (assignment in condition)
print("Ten!")
# In other languages this might silently work wrong; Python at least flags it
# ✅ Correct
if x == 10:
print("Ten!")
Infinite Loop — Forgetting to Update the Counter
# ❌ Wrong — runs forever
count = 0
while count < 5:
print(count)
# forgot count += 1 !
# ✅ Correct
count = 0
while count < 5:
print(count)
count += 1
Misplaced Indentation That Changes Behavior
# ❌ Wrong — the print runs only once, after the loop
for i in range(5):
result = i * 2
print(result) # Only prints the last result
# ✅ If you want to print every result:
for i in range(5):
result = i * 2
print(result) # Indented inside the loop
Mutable Default Arguments
This is a Python-specific trap that surprises even intermediate developers:
# ❌ Wrong — the list persists between function calls!
def add_item(item, lst=[]):
lst.append(item)
return lst
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b'] — NOT ['b']!
# ✅ Correct — use None as default, create list inside
def add_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
Off-By-One in range()
# ❌ Wrong — prints 0 to 9, not 1 to 10
for i in range(10):
print(i)
# ✅ Correct — to print 1 through 10:
for i in range(1, 11):
print(i)
How to Debug Python Code Like a Pro
Debugging is a skill just as important as writing code. Here’s a beginner-friendly process:
Step 1 — Read the Full Error Message
Don’t scroll past the red text. Read the error type and line number. Python is telling you exactly where to start looking.
Step 2 — Add Strategic print() Statements
Insert print() calls to track what your variables actually contain at each step:
def calculate_total(prices):
print(f"DEBUG: prices = {prices}") # Check what's coming in
total = sum(prices)
print(f"DEBUG: total = {total}") # Check the result
return total
Remove these once you’ve found the bug.
Step 3 — Isolate the Problem
Comment out sections of code and run smaller pieces independently. If you can reproduce the error in 5 lines, it’s much easier to fix than in 100.
Step 4 — Use Python’s Built-in Debugger
Python includes a debugger called pdb that lets you pause execution and inspect variables live:
# Add this line where you want execution to pause
breakpoint() # Python 3.7+ — no import needed
# Or the older method:
import pdb; pdb.set_trace()
Once paused, type n to go to the next line, p variable_name to print a variable, and q to quit.
Step 5 — Google the Exact Error
Copy the last line of the traceback and search it. Stack Overflow has answers to almost every common Python error a beginner will encounter.
For a full, illustrated walkthrough of the debugging process, read How to Debug Python Code Step by Step.
Best Tools for Debugging Python in 2026
You don’t have to rely on print() statements forever. Here are the tools every beginner should know:
VS Code with Python Extension (Pylance)
The best free setup for beginners. Pylance highlights errors in real time, offers intelligent autocomplete, and has a built-in visual debugger with breakpoints. You can hover over variables to see their values without running the code.
PyCharm Community Edition
A full-featured Python IDE with an exceptional debugger. Set breakpoints, step through code line by line, and watch variables update in real time. The free Community Edition is more than enough for beginners.
Pylint and Flake8
These linters analyze your code for potential problems before you run it:
pip install pylint flake8
pylint yourfile.py
flake8 yourfile.py
They catch undefined variables, unused imports, style violations, and much more.
Python Tutor
A free online tool at pythontutor.com that visualizes your code execution step by step, showing exactly how variables change and how the call stack works. Invaluable for understanding scope and loop behavior.
Mypy (Static Type Checker)
If you start using type hints (recommended!), Mypy can catch TypeErrors before runtime:
pip install mypy
mypy yourfile.py
Python Best Practices That Prevent Errors Before They Happen
The best bug is the one you never write. Here are the habits that reduce errors dramatically:
Follow PEP 8 — Python’s Style Guide
Consistent naming conventions, 4-space indentation, and clear spacing eliminate entire categories of bugs. Most IDEs can automatically format your code to PEP 8 standards.
Use Virtual Environments
Always work inside a virtual environment to keep project dependencies isolated:
# Create a virtual environment
python -m venv venv
# Activate it (Mac/Linux)
source venv/bin/activate
# Activate it (Windows)
venv\Scripts\activate
# Install packages inside the environment
pip install requests pandas
This prevents ModuleNotFoundErrors caused by installing packages in the wrong place.
Use f-Strings for String Formatting
# ❌ Old and error-prone
name = "Alice"
age = 30
print("Name: " + name + ", Age: " + str(age))
# ✅ Clean and safe
print(f"Name: {name}, Age: {age}")
Add Type Hints to Your Functions
# Without type hints — intent is unclear
def process(data, limit):
return data[:limit]
# With type hints — clear and analyzable by tools
def process(data: list, limit: int) -> list:
return data[:limit]
Handle Exceptions Specifically, Not Broadly
# ❌ Bad — hides all errors silently
try:
result = risky_operation()
except:
pass
# ✅ Good — handles specific error, lets others surface
try:
result = int(user_input)
except ValueError:
print("Please enter a valid integer.")
Write Small, Focused Functions
A function that does one thing is easy to test and easy to debug. A function that does ten things is a nightmare.
For more on writing clean, professional Python code, explore our Python Decorators Made Simple article — a great next step once you’re comfortable with the basics.
10 Quick Tips to Avoid Python Errors as a Beginner
- Read the full error message — it tells you exactly what’s wrong and where
- Use 4 spaces for indentation — never mix tabs and spaces
- Define variables before using them — Python reads top to bottom
- Use f-strings instead of string concatenation to avoid TypeErrors
- Validate all user input with
try-exceptbefore converting types - Install packages using
python -m pip installto avoid environment mismatches - Enable a linter in your IDE — Pylint and Flake8 catch mistakes before runtime
- Test in small pieces — run your code every 10-15 lines, not after 100
- Use descriptive variable names —
user_ageis better thanx - Keep the Python docs open at docs.python.org — they are the authoritative reference
Want to test your error-handling skills in a real interview context? Check out our Top 20 Python Interview Questions for Beginners (2026).
Frequently Asked Questions (FAQs)
Q1: What is the most common Python error for beginners?
SyntaxError and IndentationError are the most frequent errors new Python programmers encounter. They occur when the code violates Python’s strict formatting rules — most often a missing colon, wrong indentation, or unclosed parenthesis.
Q2: How do I fix “NameError: name is not defined”?
Make sure the variable is defined before the line where you use it. Check for spelling mistakes and ensure the variable is in the correct scope. If it should be imported from a module, check that your import statement is at the top of the file.
Q3: Why do I get ModuleNotFoundError even after installing a package?
You likely installed the package in a different Python environment than the one running your script. The fix is to use python -m pip install <package-name> — this ensures you’re installing into exactly the right interpreter.
Q4: What is the difference between TypeError and ValueError?
- TypeError = wrong type (e.g., passing a string where a number is expected)
- ValueError = right type, wrong value (e.g., passing
"abc"toint()— it’s a string, which is the right type, but"abc"can’t be converted to an integer)
Q5: How do I read a Python traceback?
Start at the bottom — the last line tells you the error type and description. Work upward through the traceback to see which functions called each other, and find where in your code the problem originated.
Q6: What’s the easiest way to catch Python errors before running code?
Install a linter. Pylint and Flake8 analyze your code without running it and highlight problems. VS Code with the Python extension does this automatically as you type.
Q7: What is a logic error in Python?
A logic error doesn’t cause a crash — it causes wrong output. Examples include using = instead of == in a condition, an off-by-one error in a range(), or forgetting to update a counter in a while loop. These are caught by careful testing, not by Python itself.
Q8: Where can I practice fixing Python errors?
The best way to learn is by writing code and debugging it yourself. Use our PyCodeRoom AI Task Generator to get custom Python challenges tailored to your current skill level, or work through our collection of 50 Python Coding Questions for Practice.
Conclusion
Python errors are not the enemy — they’re the feedback loop that makes you a better developer. Every SyntaxError, NameError, and TypeError is Python telling you something specific, in a language you can learn to read fluently.
Here’s what to take away from this guide:
- Read your tracebacks from bottom to top — the answer is almost always in the last two lines
- IndentationError and SyntaxError are structural — fix your formatting
- NameError means something isn’t defined — check spelling and order
- TypeError and ValueError are about data — check types and values before operating on them
- IndexError is about bounds — remember that Python lists start at index
0 - ModuleNotFoundError is an environment issue — use
python -m pip install - AttributeError means you’re calling the wrong method — use
dir()to explore available options - Logic errors require testing and careful reading — Python won’t warn you
