Python error IndentationError expected an indented block

+2 votes

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 folloeing error:

IndentationError: expected an indented block
Jun 17, 2019 in Python by Rhea
324,269 views
Python error  IndentationError  expected an indented block  | Edureka Community
-
Лучший сайт для покупки товаров разной направленности - Hydra (hydraruzxpnew4af). Это крупнейшая в России и СНГ торговая анонимная площадка, которая позволяет быстро и безопасно продавать и покупать вещи любого типа. Для каждого пользователя представлена масса возможностей. К тому же, у каждого продавца есть рейтинг, отзывы, и другая информация, которая поможет вам подобрать подходящее предложение. https://hydraruzspsnew4af.xyz — это лучший, и наверное, единственный сайт, на котором можно купить любые товары, независимо от вашего желания и требований. При этом Администрация проекта гарантирует анонимность и безопасность при совершении сделок. И контролирует каждую покупку, чтобы пользователей не обманывали. Именно поэтому площадка настолько востребована и популярна. гидра com

9 answers to this question.

+1 vote

Python requires its code to be indented and spaced properly. 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

Hope it helps!!

If you need to know more about Python, It's recommended to join Python course today.

Thanks!

answered Jun 17, 2019 by Varun

edited Jun 17, 2019
import pyttsx3

engine = pyttsx3.init('sapi5')
voices= engine.getProperty('voices')
print(voices[1].id)
engine.setProperty('voice', voice[1].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

    if __name__=="__main__" :

speak("Code With Harry")

Hey, @There,

Register/Sign up on the community to gain points for further contributions. You may ask questions, answer, upvote, and downvote an answer. Each of these would fetch you points and you could be among the top contributors and win exciting merchandise from Edureka. 

0 votes

Putting in an extra space or leaving one out where it is needed will surely generate an error message . Some common causes of this error include:

  •     Forgetting to indent the statements within a compound statement
  •     Forgetting to indent the statements of a user-defined function.

The error message IndentationError: expected an indented block would seem to indicate that you have an indentation error. It is probably caused by a mix of tabs and spaces. The indentation can be any consistent white space . It is recommended to use 4 spaces for indentation in Python, tabulation or a different number of spaces may work, but it is also known to cause trouble at times. Tabs are a bad idea because they may create different amount if spacing in different editors . 

Ready to unlock the power of data? Join our Data Science with Python Course and gain the skills to analyze, visualize, and make data-driven decisions.

answered Mar 2, 2020 by evanbung
• 180 points

Thank you for your simple explanation!!

0 votes
IndentationError:  what is the mean
answered Oct 14, 2020 by anonymous
• 140 points

Hello,

For your query you can refer this:https://www.edureka.co/community/80421/indentationerror-expected-an-indented-block

Hope it helps you!!

Thank You!!

Hi, @There,

Whenever you have a situation with code inside of a statement (such as the code that defines the main() function), that 'inside' code must be indented, and must be indented consistently. If you forget to indent, you'll see this error.

0 votes

In python, indentation indicates the block of code for control flow statements, class, and function definitions. The other programming languages, such as C#, JAVA, C/C++, will use braces { } to define a block of code. So, while writing the code in python, you need to follow the indentation. Please check the following resource to know about indentation importance in python.

How do i resolve the unexpected indent error in python?

answered Jun 8, 2021 by Suresh
• 140 points
0 votes

Hi Rhea,

As everyone else has mentioned, python identifies a new block of code based on indentations. 

In this case your, all the lines under your function should be indented. Then only Python can understand that these lines are the body of the function.

Try modifying your code like this:

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

Hope this helps.

answered Jun 10, 2021 by Vinay
• 140 points
0 votes
Before if and else there should be 2 spaces.
answered Aug 17, 2022 by Alex
0 votes
IndentationError: expected an indented block
The above error means you did some space error in your code or program.

answered Feb 1, 2023 by anonymous
0 votes
class Formula():
    def interest(self, P, N, R):
        self.money=P*N*R/100
        return self.money
class Tamil(Formula):
    def c1(self):
    class_name=customer1.__class__.__name__
    print(f"Enter the Details of {class_name}:")
    P=float(input("Enter the principal amount:"))
    N=int(input("Enter the number of years:"))
    R=float(input("Enter the rate of interest:"))
    self.amount = Mainkey.interest(P, N, R)
    print(f"{class_name} will be receiving Rupees {self.money} as interest.")
    print("**************")
    
class Madhu(Formula):
    def c2(self):
    class_name=customer1.__class__.__name__
    print(f"Enter the Details of {class_name}:")
    P=float(input("Enter the principal amount:"))
    N=int(input("Enter the number of years:"))
    R=float(input("Enter the rate of interest:"))
    self.amount = Mainkey.interest(P, N, R)
    print(f"{class_name} will be receiving Rupees {self.money} as interest.")
    print("**************")
    
class Sathiya(Formula):
    def c3(self):
    class_name=customer1.__class__.__name__
    print(f"Enter the Details of {class_name}:")
    P=float(input("Enter the principal amount:"))
    N=int(input("Enter the number of years:"))
    R=float(input("Enter the rate of interest:"))
    self.amount = Mainkey.interest(P, N, R)
    print(f"{class_name} will be receiving Rupees {money} as interest.")
    print("**************")
        
mainkey=Formula()
customer1=Tamil()
customer2=Madhu()
customer3=Sathiya()

customer1.c1()
customer2.c2()
customer3.c3()
answered Apr 1, 2023 by anonymous
• 140 points
0 votes
File "main.py", line 11

Exit

Width(x)

IndentationError: expected an indented b lock after 'for' statement on line 10
answered Jun 28, 2023 by anonymous

Related Questions In Python

0 votes
1 answer

I was written the python program, am getting error message "IndentationError: expected an indented block"

Hi@Thiyagarajan, You have one else block in your ...READ MORE

answered May 27, 2020 in Python by MD
• 95,460 points
3,565 views
0 votes
1 answer

I got expected an indented block error.

Hi, You used one function in your code, ...READ MORE

answered Jun 16, 2020 in Python by MD
• 95,460 points
2,526 views
0 votes
1 answer

IndentationError: expected an indented block

Hello @ nishit, Indentation means the space from margin to ...READ MORE

answered Aug 10, 2020 in Python by Niroj
• 82,840 points
5,784 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,454 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,108 views
0 votes
1 answer

Python error "TypeError: range() integer end argument expected, got numpy.float64."

Hi @Kashish, try something like this: for i ...READ MORE

answered May 27, 2019 in Python by Harish
2,986 views
0 votes
1 answer

How can I raise an exception in Python so that it can later be caught via an except block?

It's pretty simple to raise a query  raise ...READ MORE

answered May 29, 2019 in Python by Umesh
976 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP