UnsignedByte
UnsignedByte

Reputation: 887

Unexpected "expected an indented block" error on python

When I run my python program, unexpected "expected an indented block" errors keep popping up. I don't see anything wrong with the code, so please help.

def function
    if mode == 1:
    #code
    elif mode == 2:
    #code
    else:
    #code

while True:
    while True:
        #code here

Upvotes: 2

Views: 2020

Answers (3)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Each time you type : at the end of the line, Python expects a statement or expression indented in the next block.

To create an "empty" loop, use pass:

def function():
    if mode == 1:
        pass
        # code will go here
    elif mode == 2:
        pass
        # code will go here
    else:
        pass
        # code will go here

while True:
    while True:
        pass
        # code here

the error occurs at the first "While True" loop

The reason it happens, is because after the else: Python is expecting a statement or an expression, and since the first one of those is the while True:, and its not indented to be under the else: block you get that exception.

Upvotes: 5

UnsignedByte
UnsignedByte

Reputation: 887

I figured out the problem, but thanks anyway. Python needs you to put code in the if and else statements or else it will think that you forgot to indent in the rest of the code. But thanks!

Upvotes: 0

ansg191
ansg191

Reputation: 439

First of all, after def function there must be parenthesis followed by parenthesis and a colon. I'm not sure, but are you indenting after the if statements. AIs there legit code where your commenting or is that just a comment? If there is no code, it will raise an error due to the fact that there must be an indented block after a control line. For example,

def Function(mode):
    if mode == 0:
        print "mode is 0"
    elif mode == 1:
            print "mode is 1"
    else:
        print "unknown mode"
while True:
     while True:
         Function(5)
         #do What ever here

This will not raise an Exception

IMPORTANT: Make sure you break your code otherwise it will go forever.

Upvotes: 0

Related Questions