Python error IndentationError expected an indented block

25.3K    Asked by GordonGuess in SQL Server , Asked on Jul 27, 2021

 I am trying to execute the following python code:

def example(p,q):
a = p.find(" ")
b = q.find(" ")
str_p = p[0:a]
str_q = p[b+1:]
if str_p == str_q:
    result = True
else:
    result = False
return result

And I get the following error:

IndentationError: expected an indented block

Why getting a python error expected an indented block?


Answered by Michael Vaughan

Reason of getting python error expected an indented block:

In python, the expected an indented block error is caused by a mix of tabs and spaces. If you do not have appropriate indents added to the compound statement and the user defined functions, the error IndentationError: expected an indented block will be thrown.

Python requires its code to be indented and spaced properly. So make sure to never mix tabs and spaces. If you're using tabs stick to tabs and if you're using space stick to space.

Also in your code, change this part:

if str_p == str_q:
    result = True
else:
    result = False
return result
To
return str_p == str_q

Your Answer

Answer (1)

The "IndentationError: expected an indented block" is a common error in Python that occurs when the interpreter encounters a line of code that should be indented within a block but finds that the line is not indented properly or not indented at all.


Here's an example of code that might trigger this error:if condition:
print("Condition is true") # This line should be indented within the block

To resolve this error, you need to ensure that all lines within a block are properly indented. In Python, indentation is crucial for defining the structure of the code, such as loops, conditional statements, and function definitions. Here's the corrected version of the code:

if condition:
    print("Condition is true") # Proper indentation

In this corrected version, the print statement is indented with four spaces (or a tab), indicating that it belongs to the block defined by the if statement.








8 Months

Interviews

Parent Categories