Incorrect indentation #
Python uses indentation to define the structure and hierarchy of code blocks. It helps to visually represent nested blocks of code, such as if statements, loops, and function definitions.
Incorrect indentation occurs when the spacing or tabulation used for indentation is inconsistent or does not match the expected structure. Python considers indentation as part of its syntax, so errors in indentation can lead to IndentationError or SyntaxError messages.
To identify incorrect indentation errors, carefully review the indentation level of your code. Look for inconsistencies such as mixing tabs and spaces, mismatched indentation levels within the same block, or missing or excessive indentation.
For example:
def is_positive_or_negative(num):
if num > 0:
print("The number is positive.")
else:
print("The number is negative.")
In the example above, the indentation after the first if is incorrect. Calling the function above will make the program fail to run with the error message below:
File "main.py", line 3
print("The number is positive.")
^
IndentationError: expected an indented block after 'if' statement on line 2
Exercise #
- Fix incorrect indentation in the code so that the program runs without any errors.
Tests #
is_positive_or_negative(1)should print out the message"The number is positive."is_positive_or_negative(-1)should print out the message"The number is negative."
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules