Common bugs in Python and how to fix them: IndentationError to RecursionError

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Common Python Errors: Causes and Fixes

Errors in code are an inevitable part of the learning and practice of any programmer. Python, with its dynamic typing and concise syntax, allows you to identify many errors during program execution. In this article, we will look at the most common types of errors in Python that novice developers face, and suggest effective methods for correcting them, relevant for 2025. We will also discuss modern debugging tools available in the most popular IDEs, such as VS Code and PyCharm, as well as the features provided by cloud development environments.

IndentationError: Indentation Error

IndentationError is one of the most frequent errors, especially among beginners. In Python, indentation plays a key role in determining the structure of code blocks.

Causes:

  • Missing indents: Lack of indents after function definitions, loops, conditional operators, and classes.
  • Mixing spaces and tabs: Using different types of indents in the same code block.
  • Incorrect indentation level: Inconsistent number of spaces in indents.

Fixes:

  • Use 4 spaces: Use exactly four spaces for indents, as specified in the PEP 8 standard.
  • Avoid mixing spaces and tabs: Configure your code editor to automatically replace tabs with spaces.
  • Indent visualization: Enable the indent visualization feature in the code editor (e.g., VS Code, PyCharm) to visually control the code structure. Many modern IDEs, including cloud platforms, provide tools for automatic code formatting, which helps to avoid such errors.
  • Automatic code formatting: Use automatic code formatting tools such as Black or autopep8, which automatically bring your code into compliance with the PEP 8 standard.

Example:

Incorrect:

def greet():
print("Hello, World!") # Error: missing indent

Correct:

def greet():
    print("Hello, World!") # Correct indent

SyntaxError: Incorrect Syntax

SyntaxError is a signal that there is a syntax error in the code, due to which the Python interpreter cannot understand what you are trying to do.

Causes:

  • Missing elements: Missing closing parentheses, quotes, or colons.
  • Incorrect order of expressions: Violation of the syntactic rules of the language.
  • Use of reserved words: Attempting to use Python keywords as variable names.
  • Incorrect string formatting: Errors in the definition of string literals.

Fixes:

  • Careful check: Carefully study the line indicated in the error message.
  • Completeness of constructions: Make sure that all code constructions (parentheses, quotes, colons) are completed correctly.
  • Syntax highlighting: Use a code editor with syntax highlighting, which visually highlights syntactic elements and helps to detect errors. Modern IDEs offer advanced static code analysis tools that help to identify syntax errors even before the program is run.
  • Linters: Integrate linters such as flake8 or pylint into your development process. Linters analyze your code for compliance with style standards and identify potential syntax errors.

Example:

Incorrect:

if True print("Yes") # SyntaxError

Correct:

if True:
    print("Yes")

NameError: Name not defined

NameError occurs when a program attempts to use a variable that has not been defined. This is common among novice programmers.

Causes:

  • Undefined variable: Using a variable before it is defined.
  • Typo in variable name: Incorrect spelling of a variable name.
  • Scope: Attempting to use a variable declared inside a function outside of it.

Fixes:

  • Definition before use: Make sure the variable is defined before use.
x = 10
print(x)
  • Checking the variable name: Make sure the variable name is spelled correctly.
user_name = "Alice"
print(user_name)
  • Scope: If a variable is defined in a function, use the return statement to return the value or declare the variable as global (should be used with caution).
def calculate():
    result = 42
    return result
x = calculate()
print(x)

TypeError: Unsupported operand type

TypeError occurs when an operation or function is applied to an object of an inappropriate type.

Example:

x = "5"
result = x + 5 # TypeError: can only concatenate str (not "int") to str

Causes:

  • Mismatch of data types: Attempting to perform an operation that is not supported for the specified data types.
  • Incorrect use of functions: Passing arguments of the wrong type to the function.

Fixes:

  • Type Conversion: Explicitly convert data types using int(), float(), str(), etc.
x = "5"
result = int(x) + 5
print(result)
  • Type checking: Use the type() function to check the types of variables before performing operations.
  • Type annotations: Starting with Python 3.5, you can use type hints to specify the expected types of arguments and return values of functions. This allows static code analyzers (e.g., mypy) to detect type errors during development.
def add(a: int, b: int) -> int:
    return a + b

TypeError: 'int' object is not callable

This error occurs when you try to call an int object as a function.

Causes:

  • Name redefinition: A variable with a numeric value has been redefined as a function or vice versa.
  • Incorrect use of parentheses: Attempting to call a variable that is not a function with parentheses.

Fixes:

  • Avoid redefining names: Do not use the names of built-in functions (e.g., len, list, str, int) as variable names.
  • Checking variable values: Make sure the variable contains a value of the expected type.
  • Remove extra parentheses: If a variable stores a number, do not put parentheses after it.

Example:

Incorrect:

len = 5
print(len("text")) # Causes an error, len is no longer a function

Correct:

length = len("Hello")
print(length)

KeyError: Missing key in dictionary

KeyError occurs when you try to access a key in a dictionary that does not exist.

Causes:

  • Non-existent key: Attempting to access a key that is missing from the dictionary.
  • Typo in the key: Incorrect spelling of the key name.
  • Incomplete data: Working with a dictionary that does not contain the necessary data.

Fixes:

  • Checking for the presence of a key: Use the in operator to check for the presence of a key in the dictionary before accessing it.
user = {"name": "Alice", "age": 30}
if "email" in user:
    print(user["email"])
else:
    print("Email is not specified.")
  • Get() method: Use the get() method with a default value to be returned if the key is missing.
user = {"name": "Alice", "age": 30}
print(user.get("email", "Email not found"))
  • defaultdict: Use defaultdict from the collections module to automatically create keys with default values the first time they are accessed.
from collections import defaultdict
user = defaultdict(lambda: "Unknown")
user["name"] = "Alice"
print(user["email"]) # Will print "Unknown" instead of an error

Effective methods of debugging code in Python

Debugging is the process of finding and fixing errors in code. Competent debugging saves time and helps to quickly find the cause of the problem. In 2025, many tools and techniques are available for effective debugging of Python code, including improved integration capabilities with cloud platforms.

Using the print() function

The easiest and most popular way to debug is to add print() statements to track the values of variables during program execution.

def calculate(a, b):
    result = a + b
    print(f"DEBUG: result = {result}")
    return result

Pdb Module (Python Debugger)

The built-in pdb module provides an interactive debugger that allows you to control program execution, set breakpoints, and view variable values.

import pdb

def test():
    a = 5
    pdb.set_trace() # Set a breakpoint
    b = 10
    print(a + b)

test()

Key pdb commands:

  • n: Go to the next line.
  • c: Continue program execution.
  • q: Exit debugging.
  • p variable: Print the value of the variable.

Debugging Tools in IDEs

Modern IDEs (VS Code, PyCharm) offer convenient debugging tools, including the ability to set breakpoints, step through code, and view variable values in real time.

Cloud Debuggers

Many cloud development platforms, such as Google Colab and AWS Cloud9, provide built-in debuggers that allow you to debug code directly in the cloud.

AssertionError: Assertion check

AssertionError occurs when a condition set by the assert operator is violated. This construct is used to automatically check the correctness of values during program execution.

x = 5
assert x > 0, "Value must be positive"

Why use assert?

  • Checking preconditions in functions.
  • Testing code.
  • Debugging complex algorithms.

Example of checking function parameters:

def calculate_discount(price, discount):
    assert price >= 0, "Price must be non-negative"
    assert 0 <= discount <= 1, "Discount must be between 0 and 1"
    return price * (1 - discount)

print(calculate_discount(100, 0.2)) # Works
# print(calculate_discount(-100, 0.2)) # AssertionError

Important:

  • Use assert only during debugging and development.
  • In production code, use full error handling through if and exceptions.

RecursionError: Maximum recursion depth exceeded

RecursionError occurs when a function calls itself too many times and the call stack overflows.

def infinite_recursion():
    return infinite_recursion()

infinite_recursion() # RecursionError: maximum recursion depth exceeded

By default, in Python, the recursion depth is limited to 1000 calls.

How to avoid this error?

  • Termination condition: Make sure the recursion has a termination condition (base case).
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(5)) # Works correctly
  • Iteration instead of recursion: Use iterative solutions instead of recursion, if possible.
def factorial_iterative(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result
  • Increasing the recursion limit: If necessary, increase the recursion depth limit (not recommended without extreme need).
import sys
sys.setrecursionlimit(2000)

Remember: Increasing the recursion depth can lead to memory overflow.

Conclusion

Errors in Python are an integral part of the development process. It is important not to be afraid of them, but to learn to analyze and eliminate them. Modern debugging tools and techniques available in IDEs and cloud platforms greatly simplify this process. Understanding common types of errors and how to fix them will help you write more reliable and high-quality code.

  • KeyError: Check for the presence of keys in dictionaries and use the .get() method.
  • Debugging code: Use print(), the pdb module, and the capabilities of your IDE.
  • AssertionError: Apply assert to check assumptions in your code.
  • RecursionError: Always write out the base cases in recursive functions and do not abuse deep recursion.

By following these guidelines and using modern tools, you can significantly increase your productivity and the quality of the code you develop in Python.

News