Menu
Coddy logo textTech

Indentation Errors

Part of the Logic & Flow section of Coddy's Python journey — lesson 27 of 78.

In Python, proper indentation is crucial for defining the scope of blocks of code, such as loops, functions, and conditional statements. Incorrect indentation can lead to errors or unexpected behavior. These errors are known as IndentationError.

Correct Indentation:

if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

Incorrect Indentation:

if x > 5:
print("x is greater than 5")  # This will cause an IndentationError
else:
    print("x is not greater than 5")

In the incorrect example, the print statement inside the if block is not properly indented, which will result in an IndentationError. Consistent and correct indentation is essential for writing valid Python code.

Cheat sheet

Python uses indentation to define code blocks. Incorrect indentation causes IndentationError.

Correct indentation:

if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

Incorrect indentation:

if x > 5:
print("x is greater than 5")  # IndentationError
else:
    print("x is not greater than 5")

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow