Python is beginner-friendly, but every programmer still makes mistakes. Errors are not proof that you are bad at coding. They are information that helps you understand what the interpreter expected and what your program actually did.
This guide explains seven common Python errors and habits that frequently slow beginners down. You will see broken examples, corrected versions, and practical strategies for diagnosing problems instead of changing code randomly.
First, Learn to Read a Traceback
When Python stops with an exception, it prints a traceback. Read it from the bottom upward. The last line contains the exception type and message. The lines above show the chain of function calls and the file and line where the failure occurred.
Traceback (most recent call last):
File "app.py", line 4, in <module>
result = 10 / value
ZeroDivisionError: division by zeroThis message identifies the exception, the file, the line number, and the expression. Reproduce the problem with the smallest possible input, inspect the values involved, and fix the cause rather than hiding the message. The official Python errors and exceptions tutorial is an excellent reference.
1. Incorrect Indentation
Indentation defines blocks in Python. Code inside an if, loop, function, class, or exception handler must be consistently indented.
age = 20
if age >= 18:
print("Adult")This produces an IndentationError. The statement belongs inside the conditional block:
age = 20
if age >= 18:
print("Adult")Use four spaces per level and configure your editor to insert spaces rather than mixing tabs and spaces. Automatic formatting tools can catch inconsistent style. The PEP 8 guide explains common layout conventions.
2. Forgetting That input() Returns Text
The input() function always returns a string. Adding that text directly to an integer causes a TypeError.
age = input("Age: ")
next_year = age + 1Convert the value before arithmetic and handle invalid input:
try:
age = int(input("Age: "))
print(f"Next year you will be {age + 1}.")
except ValueError:
print("Enter a whole number.")Use float() for decimal input and int() for whole numbers. The dedicated Python input() guide covers validation patterns in more depth.
3. Choosing the Wrong Data Structure
Lists, tuples, sets, and dictionaries have different purposes. A list preserves order and can contain duplicates. A tuple is immutable. A set stores unique hashable values. A dictionary maps keys to values.
# A list is awkward for repeated membership checks
blocked_users = ["ana", "leo", "mia"]
if "leo" in blocked_users:
print("Blocked")The code works, but a set better expresses uniqueness and normally provides faster membership checks:
blocked_users = {"ana", "leo", "mia"}
if "leo" in blocked_users:
print("Blocked")Use a dictionary when records need labels:
product = {
"name": "Keyboard",
"price": 89.90,
"stock": 12,
}
print(product["name"])Read the Python sets guide and the broader Python data types guide before forcing every problem into a list.
4. Catching Every Exception Without Understanding It
Exception handling keeps a program from failing unexpectedly, but a broad empty handler can hide real bugs.
try:
value = int(user_text)
except:
passThis discards useful information. Catch the expected exception and provide an appropriate response:
try:
value = int(user_text)
except ValueError as exc:
print(f"Invalid integer: {exc}")Different failures need different actions. A missing file may require a new path; invalid input should be requested again; a database outage may need a retry or alert. The complete try and except guide explains else, finally, custom exceptions, and exception chaining.
5. Writing Everything in One Long Script
A program may begin with ten lines and grow to hundreds. When all logic stays at the top level, repeated code appears, variables become difficult to track, and testing individual behavior becomes painful.
name = input("Name: ")
age = int(input("Age: "))
print(f"Hello {name}, you are {age} years old.")Move clear responsibilities into functions:
def read_age() -> int:
while True:
try:
return int(input("Age: "))
except ValueError:
print("Enter a whole number.")
def greet(name: str, age: int) -> str:
return f"Hello {name}, you are {age} years old."
name = input("Name: ").strip()
age = read_age()
print(greet(name, age))Each function now has one job and can be tested separately. Continue with the Python functions guide.
6. Installing Every Package Globally
Different projects may require different versions of the same library. Global installation makes dependencies collide and creates the familiar problem of code working on one computer but not another.
python -m venv .venvActivate the environment, install only the project’s dependencies, and record them:
# Windows
.venv\Scripts\activate
# macOS or Linux
source .venv/bin/activate
python -m pip install requests
python -m pip freeze > requirements.txtUse python -m pip to make it clearer which interpreter owns the installed package. The venv guide includes activation commands and editor configuration. For missing packages, see how to fix ModuleNotFoundError.
7. Ignoring Naming, Formatting, and Documentation
Code that runs is not automatically easy to maintain. Unclear names, giant functions, unexplained constants, and outdated comments create bugs later.
# Hard to understand
def c(a, b):
return a * b * 0.15A clearer version communicates intent:
TAX_RATE = 0.15
def calculate_tax(price: float, quantity: int) -> float:
"""Return the tax for a product order."""
subtotal = price * quantity
return subtotal * TAX_RATEUse descriptive snake_case names for functions and variables, constants in uppercase, useful docstrings, and comments that explain why rather than restating what the code says. The guides to Python comments and Python docstrings provide practical examples.
Other Frequent Exceptions
NameError
A variable or function name does not exist in the current scope. Check spelling and whether the assignment ran before use.
total = 25
print(totla) # NameError: typoIndexError
A sequence index is outside its valid range.
colors = ["blue", "green"]
print(colors[2])Inspect len(colors), use loops rather than manual indexes when possible, or validate the index first.
KeyError
A dictionary does not contain the requested key.
user = {"name": "Sam"}
print(user["email"])Use get() when absence is expected:
email = user.get("email")
if email is None:
print("No email registered")AttributeError
An object does not have the requested attribute or method. Check its type and the method name.
number = 10
number.append(5) # integers have no append methodA Reliable Debugging Process
- Read the complete traceback, especially the final line.
- Open the exact file and line mentioned.
- Inspect the value and type of every variable in that expression.
- Reduce the problem to a small reproducible example.
- Check the official documentation for the function or exception.
- Change one thing at a time.
- Add a test that prevents the bug from returning.
The official built-in exceptions reference lists the meaning and inheritance of standard exception classes. For automated regression tests, use the Pytest beginner guide.
Use print() Carefully for Debugging
Temporary output can reveal values and execution flow:
def calculate_average(values):
print(f"DEBUG values={values!r}")
total = sum(values)
print(f"DEBUG total={total}")
return total / len(values)Remove noisy prints or replace them with logging before production. The f-string debugging guide shows the useful debug specifier.
Frequently Asked Questions
What is the most common beginner error?
Indentation and type conversion are among the first recurring problems because Python uses indentation for blocks and input() returns text.
Should I catch Exception everywhere?
No. Catch specific, expected exceptions near the operation that can fail. Let unexpected programming errors remain visible during development.
Why does code work in one terminal but not another?
The terminals may use different Python interpreters or virtual environments. Check the active interpreter and install dependencies inside the project environment.
Is PEP 8 mandatory?
Python does not require it to execute code, but consistent style improves readability, reviews, teamwork, and maintenance.
How do I become better at debugging?
Practice reading tracebacks, isolate small examples, verify types and assumptions, and write tests for every corrected bug.
Conclusion
The fastest way to improve is not to avoid every error but to understand each one. Use consistent indentation, convert external input, choose appropriate data structures, handle expected exceptions, organize logic into functions, isolate dependencies, and follow clear style conventions. These habits turn confusing failures into precise, manageable problems.






