Skip to content Skip to sidebar Skip to footer

Syntax Error For If And Else Statements

enter image description hereOk, I am just starting to learn python, and I can't figure out why my IF/Else statement keeps getting this error after I enter Else: 'SyntaxError: unind

Solution 1:

Ah, IDLE. You have tried to enter this into shell, right? So the thing looks like

>>> if x > 1000:
        print(3)
    else:

right? The point is, >>> doesn't count when calculating indents. So in fact if and else are not in the same column as far as IDLE is concerned. :-( [The indents it sees are 0, 8, 4.] You have to start the else: flush completely to the left margin.

Solution 2:

Be careful with spaces and tabs, even if lines look visually indented, from python perspective they maybe are not indented

enter image description here

For example, look at the image, line 2 contains 4 spaces and line 6 contains one tab. It's really useful when your text editor allows you to notice these differences somehow.

Solution 3:

Each indentation level should have four spaces.

if x > 1000:
    print('3')
else:
    pass  # Must match indentation level of `print('3')` above.


Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:52:12) 
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>>x = 50>>>if x > 100:...print('3')...else:...pass...>>>x = 150>>>if x > 100:...print('3')...else:...pass... 
3

Thanks to the pointer from @Vekyn regarding IDLE indentation quirks:

enter image description here

Solution 4:

You are probably mixing up spaces and tabs. Only use one of those. If you are using spaces, make sure you are using the same amount of spaces. Also else must have something in it, like pass or return

Post a Comment for "Syntax Error For If And Else Statements"