1

Hello there I'm currently trying to get a good grasp of the if, elif, else structure in Python. I'm trying some weird combinations in python having a test program to know the output in this if, if, elif, elif, else code. However I'm getting weird results such as this

input = raw_input('Please enter the required digit: ')
intput = int(input)

if intput == 0:
    print 'if1'

if intput == 1:
    print 'if2'
elif intput == 0:
    print 'elif1'
elif intput == 1:
    print 'elif2'
else:
    print 'else'

if I in put 1 it will print "if2", I thought that it will also print "elif2" and other shenanigans when I try to change the "intput == n" code. So my question is do I have to stick to the if,elif, elif, .... n * elifs, else method which seems to me working alright than working with the wacky if,if.... n * ifs, elif, elif, ...n* elifs, else.

Thanks

2
  • 3
    elif's are only evaluated if the preceding if/elif statement is False, if you had all if statements then they would all be evaluated, if none are True then the else statement will be executed. Commented Aug 25, 2014 at 12:08
  • Thanks for the insight will tinker with it Commented Aug 25, 2014 at 12:13

2 Answers 2

8

The elif tree is designed such that at anywhere along if one of the statement turns out to be True, the rest of the elifs will not be evaluated.

Here's a tutorial that might help you understand if else better.

Sign up to request clarification or add additional context in comments.

Comments

0

this may be more clear to understand:

if input == 0:
    print "if1"

switch(input):
    case 1:
        print "if2"
        break
    case 0:
        print "elif1"
        break
    case 1:
        print "elif2"
        break
    default:
        print "else"
        break

of course, the code does not work.

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.