0

I am newbie to Python and programming environment .Now I am studying python via online .I Landed up a small trouble while studying If Statements . The IF statement is currently interpreting while the ELSE statement is written it displays me a syntax error attached Screen Shot will make my problem understandble more clearly:enter image description here

not only ELSE statement even ELIF statement also displays a syntax error.

1
  • 2
    Spacing is the main thing in Python. you need to intend your code properly :) Commented Dec 6, 2013 at 5:43

3 Answers 3

3

the if and else need to be indented the same amount

for example

x = 5
if 8 > x:
    print "8 is greater than x"
else:

same goes for elif

x = 5
if 8 > x:
    print "8 is greater than x"
elif 8 < x:
    print "8 is less than x"
else:
Sign up to request clarification or add additional context in comments.

2 Comments

It follows indentations for code blocks.In other languages we have '{}' for code blocks.
@codehorse I edited your post to actually fix the indentation.
3

Indentation is everything in python. By

if x%2==0:
    print "even"
    else:
    ^^^

You mean to say that the else statement also comes under the if block, as it is one block of indent after the if statement. This throws an error as there is no if for the else that you have given. Now lets come to the correct way:

if x%2==0:
    print "even"
else:
    print "odd"

Here, since if and else are in the same indent, the else is corresponding to the if, and the else is executed if the if condition fails.

Comments

1

Check your spacing, else should be under if

if (x%2 == 0):
    print "x is even"
else:
    print "x is odd"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.