if ... else ... elif

How to make an If else statement?

my statement is:


if h < 0:
   h = 30

But is doesn’t work!

what doesn’t work?

if cond1:
  foo()
  foobar()
  ...
elif cond2:
  foo1()
  ...
else:
  foo3()
  ...

[color=green]What does the elif do exactly. I know the else and if’s, but this is the first time I’ve heard of elif.

its short for the c statement “else if”, in such a if, elif, else tree, the code first matches the first if condition, then the elif condition, if both are false, the code runs the else option as default behavior.


i = 2

if ( i == 1) 
    # if i equals 1, do this
    print "doing the if stuff"
elif ( i == 2) 
    # if i does not equal 1, but DOES equal 2 do this
    print "doing elif stuff"
else: 
    # if neither of the above conditions are correct, do this
    print "doing else stuff"

in this case, the elif function would be executed

the reason for using elif is just the following:

With elif:


i = 2

if ( i == 1)
    # if i equals 1, do this
    print "doing the if stuff"
elif ( i == 2)
    # if i does not equal 1, but DOES equal 2 do this
    print "doing elif stuff"
else:
    # if neither of the above conditions are correct, do this
    print "doing else stuff" 

Without elif but with nearly the same cpu usage:

i = 2

if ( i == 1):
    # if i equals 1, do this
    print "doing the if stuff"
else:
        if ( i == 2):
            # if i does not equal 1, but DOES equal 2 do this
            print "doing elif stuff"
        else:
            # if neither of the above conditions are correct, do this
            print "doing else stuff" 

(I guess you can imagine how this will look if you use more than just 2 "if"s)

Without all the sorting it will look similar to the original version:

i = 2

if ( i == 1)
    # if i equals 1, do this
    print "doing the if stuff"
if ( i == 2)
    # if i does not equal 1, but DOES equal 2 do this
    print "doing elif stuff"
else:
    # if neither of the above conditions are correct, do this
    print "doing else stuff" 

But in that case python has to check each if state. Always. Even if i==1, it will check for i==2, which will just create useless cpu load. (with elif it will skip the i==2 comparison like it does in the else-if-statement in the middle example.

Regards, Bigfoot29

[size=75][color=green]Okay thanks.[/size]