Online Tools Toolshu.com Log In Sign Up

10 Most Common Python Beginner Mistakes: Why They Happen and How to Fix Them

Original Author:bhnw Released on 2026-04-09 13:11 3 views Star (0)

Got an Error — and Have No Idea What Went Wrong?

When you're starting out with Python, the most frustrating moment isn't when you can't write the code — it's when you write it, hit run, and the terminal fills with red. The error message looks like a foreign language.

Here's the thing: Python's error messages are actually very informative. Most errors follow clear patterns. This article breaks down the 10 most common beginner errors, explaining why each happens and how to fix it — so red text stops feeling like the end of the world.


1. IndentationError: Indentation Problems

Error examples:

IndentationError: expected an indented block
IndentationError: unexpected indent

Why it happens: Python uses indentation to define code blocks instead of curly braces. Inconsistent indentation — or missing indentation where it's required — triggers this error.

# Wrong: the code block after if is not indented
if True:
print("hello")   # ← this line must be indented

# Wrong: mixing tabs and spaces
if True:
    print("hello")  # 4 spaces
    print("world")  # 1 tab (looks the same, isn't)

Fix: Use 4 spaces consistently and never mix tabs and spaces. Enable "show whitespace characters" in your editor to make this visible instantly.


2. NameError: Variable Not Defined

Error example:

NameError: name 'x' is not defined

Why it happens: You're using a variable that was never assigned a value, or you mistyped the name.

# Wrong 1: using before defining
print(name)
name = "Alice"

# Wrong 2: typo
username = "Alice"
print(usrname)   # ← missing a letter

Fix: Make sure variables are assigned before they're used, and double-check spelling. Python is case-sensitive — Name and name are two completely different variables.


3. TypeError: Wrong Types

Error examples:

TypeError: can only concatenate str (not "int") to str
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Why it happens: You performed an operation on incompatible types. The most common case is mixing strings and numbers.

# Wrong: concatenating a string with a number
age = 18
print("I am " + age + " years old")   # ← age is int, can't concatenate directly

# Wrong: math on a string
score = "90"
print(score + 10)   # ← score is a string

Fix: Convert types explicitly, or use f-strings:

age = 18
print(f"I am {age} years old")            # f-string — recommended
print("I am " + str(age) + " years old")  # explicit conversion

score = "90"
print(int(score) + 10)   # convert string to number first

4. IndexError: List Index Out of Range

Error example:

IndexError: list index out of range

Why it happens: You accessed a position that doesn't exist in the list. Python lists are zero-indexed — a list of length n has valid indices 0 through n-1.

fruits = ["apple", "banana", "cherry"]
print(fruits[3])   # ← only 0, 1, 2 exist — no index 3
print(fruits[-4])  # ← negative indexing starts at -1; -4 is out of range

Fix:

fruits = ["apple", "banana", "cherry"]
print(len(fruits))   # check the length first: 3
print(fruits[2])     # last element
print(fruits[-1])    # also the last element — preferred style

5. KeyError: Dictionary Key Doesn't Exist

Error example:

KeyError: 'email'

Why it happens: You tried to access a key that isn't in the dictionary.

user = {"name": "Alice", "age": 28}
print(user["email"])   # ← no 'email' key in this dictionary

Fix option 1: Use .get() — returns a default value instead of raising an error:

print(user.get("email"))              # returns None
print(user.get("email", "not set"))   # returns the default value

Fix option 2: Check whether the key exists first:

if "email" in user:
    print(user["email"])

6. AttributeError: Method or Attribute Doesn't Exist

Error examples:

AttributeError: 'str' object has no attribute 'append'
AttributeError: 'NoneType' object has no attribute 'split'

Why it happens: You called a method on an object that doesn't have it. The two most common causes: using a method from the wrong type, or calling a method on None.

# Wrong 1: strings don't have append (that's a list method)
name = "Alice"
name.append("!")   # ← str has no append

# Wrong 2: function returned None, then chained a method call
result = print("hello")   # print returns None
result.upper()             # ← None has no upper method

Fix: Know what type your variable actually is before calling methods. When you see NoneType, trace back to where the value was assigned and check whether the source really returned what you expected.


7. ValueError: Value Is Illegal

Error examples:

ValueError: invalid literal for int() with base 10: 'abc'
ValueError: not enough values to unpack

Why it happens: A function received an argument of the right type but with an invalid value.

# Wrong 1: converting a non-numeric string to int
num = int("abc")    # ← "abc" is not a number

# Wrong 2: unpacking mismatch
a, b, c = [1, 2]   # ← 3 variables on the left, only 2 values on the right

Fix:

# Validate before converting
s = "abc"
if s.isdigit():
    num = int(s)
else:
    print("not a number")

# Match the number of variables when unpacking
a, b = [1, 2]            # correct
a, *rest = [1, 2, 3, 4]  # use * to collect remaining values

8. ZeroDivisionError: Dividing by Zero

Error example:

ZeroDivisionError: division by zero

Why it happens: The denominator in a division is zero. Simple in theory, but in real projects the denominator often comes from user input or a calculation — making it hard to predict.

total = 0
average = 100 / total   # ← denominator is zero

Fix: Check the denominator before dividing:

total = 0
if total != 0:
    average = 100 / total
else:
    average = 0   # or whatever default makes sense

9. FileNotFoundError: File Doesn't Exist

Error example:

FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'

Why it happens: The file path is wrong, or the file genuinely doesn't exist.

with open("data.txt", "r") as f:   # ← no data.txt in the current directory
    content = f.read()

Fix:

import os

# Check first
if os.path.exists("data.txt"):
    with open("data.txt", "r") as f:
        content = f.read()
else:
    print("File not found")

# Or use a try-except
try:
    with open("data.txt", "r") as f:
        content = f.read()
except FileNotFoundError:
    print("File not found — check the path")

Path tip: Python's current working directory isn't necessarily where your script lives. Use os.getcwd() to print it and confirm.


10. RecursionError: Recursion Depth Exceeded

Error example:

RecursionError: maximum recursion depth exceeded

Why it happens: A function calls itself without a proper stopping condition, causing infinite recursion until the call stack overflows.

# Wrong: no base case
def countdown(n):
    print(n)
    countdown(n - 1)   # ← never stops

countdown(5)   # will recurse until it crashes

Fix: Always include a clear base case — the condition where recursion stops:

def countdown(n):
    if n <= 0:          # ← base case
        print("Done!")
        return
    print(n)
    countdown(n - 1)

countdown(5)

Want to Test a Fix Right Now?

Reading the error message is the first step — but sometimes you just need to run the corrected code immediately. Paste it into the Online Python Runner, hit Ctrl+Enter, and see the result instantly. Python 3.12, full standard library, no setup needed.

发现周边 发现周边
Comment area

Loading...