offsuure
offsuure

Reputation: 11

Python Shell not letting me create an else statement?

Whenever I try to create an else statement, the shell automatically indents under the print statement,and if I put an else statement it says the following:

if marks<=40:
    print("failed")
else:

SyntaxError: invalid syntax
>>>  

So I would try to move the else by getting it inline with the previous if statement, but it says this

>>> if marks <=40:
        print ("failed")
    else:

SyntaxError: unindent does not match any outer indentation level
>>>  

Any ideas of the problem? Thanks in advance

I'm also using v3.5.1 on a mac if that matters.

Upvotes: 1

Views: 74

Answers (1)

Rikka
Rikka

Reputation: 1049

Add a pass statement to the else branch to skip it:

if condition:
    do something
else:
    pass # Do nothing. 

The colon after else declares the start of an indented block, the interpreter will complain if it fails to find one. That's why you need at least one indented statement after the colon.

Also the else statement should be at the same indentation level as the if statement.

A typical Python shell looks like the following:

>>> if 1:
...   print 1
... else:
...   print 2
...
1
>>>

Upvotes: 2

Related Questions