What is unexpected indent in Python?

An "IndentationError: unexpected indent" in Python occurs when there is an incorrect or unexpected indentation in your code. Python relies on indentation to determine the structure and nesting of code blocks, such as loops, conditionals, and function definitions. If the indentation does not match the expected structure, Python raises this error. Let's see some examples and how to resolve them:

Incorrect Indentation

def print_numbers(): for i in range(5): print(i)

In this example, the indentation level of the print(i) statement is one level deeper than the for loop. Python expects statements inside a loop to be indented, but the print(i) statement is not indented correctly, leading to the "IndentationError: unexpected indent" error.

To fix this, ensure that all statements inside the for loop have the same indentation:

def print_numbers(): for i in range(5): print(i)

Mixing Tabs and Spaces

def print_numbers(): for i in range(5): print(i)

In this example, the print(i) statement appears to be indented with a mix of tabs and spaces. Python requires consistent indentation, either tabs or spaces, but not both. Mixing tabs and spaces can lead to this indentation error.

To resolve this issue, choose one indentation style and apply it consistently throughout your code:

def print_numbers(): for i in range(5): print(i)

Incorrectly Aligned Code Block

def is_even(num): if num % 2 == 0: return True else: return False

In this example, the if statement is not properly indented under the function definition. Python expects the code block inside the function to be indented, but the if statement is not aligned correctly.

To fix this, ensure that the code block inside the function is consistently indented:

def is_even(num): if num % 2 == 0: return True else: return False

Javascript String length

Python Indentation

Most programming languages permit indentation , but don't enforce it. Python enforces it with an iron fist. This is different from many other programming languages that use curly braces {} to delimit blocks such as C, C++, Java and Javascript. Because of this, Python users must pay close attention to when and how they indent their code because whitespace matters. Python's use of indentation comes directly from ABC . ABC is an interactive programming language and environment for personal computing, originally intended as a good replacement for BASIC .

Conclusion

An "IndentationError: unexpected indent" in Python can be resolved by carefully inspecting and correcting the indentation levels in your code. Ensure that code blocks are consistently indented, avoid mixing tabs and spaces, and make sure that statements inside loops, conditionals, or function definitions are appropriately aligned. Following these practices will help you avoid the "IndentationError" and maintain a clear and readable Python codebase.