Invalid syntax in VERY SIMPLE Python if ... else statement

Can someone explain why I get an invalid syntax error from the Python interpreter when wording this simple if ... else statement? I do not add any tabs myself, just type in the text and press Enter after entering. When I type input after "else:", I get an error. "Else" is highlighted by the interpreter. What's wrong?

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> if 3 > 0: print("3 greater than 0") else: SyntaxError: invalid syntax >>> 
+4
source share
6 answers

Python does not allow empty blocks, unlike many other languages ​​(because it does not use curly braces to indicate a block). The pass keyword should be used anytime you want to have an empty block (including if / else statements and methods).

For instance,

 if 3 > 0: print('3 greater then 0') else: pass 

Or an empty method:

 def doNothing(): pass 
+6
source

This is because your else part is empty and also not formatted with if .

 if 3 > 0: print "voila" else: pass 

In python pass equivalent to {} used in other languages ​​such as C.

+8
source

The else block must be indented as if :

 if 3 > 0: print('3 greater then 0') else: print('3 less than or equal to 0') 
+4
source

The else keyword should be indented relative to the if , respectively

eg.

 a = 2 if a == 2: print "a=%d", % a else: print "mismatched" 
+2
source

Click to open image

The only problem is retreat.

You are using IDLE. When you press the enter button after the given expression to print is another value, like the default print, it is not. You need to go to the beginning of another sentence and click once. Check the attached image, what I mean.

0
source

this is an obvious mistake that we make when we press enter after the if statement is included in this intent, try to save the else statement as direct with the if.it expression is a common typographical error

0
source

All Articles