2015年9月3日 星期四

[RR Python] else statement after while clause

As a C/C++ programmer, it's comfortable to use "while" to loop until certain expected condition happens in python, until I found that it's possible to have "else" after while loop.

there is good example at stackoverflow

and I tried this

vault = [1,2,3]

print "Start"

while vault:
    x = vault.pop(0)
    if x != None:
        print x
    else:
        print "BREAK"
        break
else:
    print "ELSE"
   
print "END"

and the result is
Start
1
2
3
ELSE
END

if change vault to [1,2,3,None]
vault = [1,2,3, None]

print "Start"

while vault:
    x = vault.pop(0)
    if x != None:
        print x
    else:
        print "BREAK"
        break
else:
    print "ELSE"
   
print "END"
the result is
Start
1
2
3
ELSE
END

The "else" can also apply to "for" loop. In short, if the loop test fails, "else" clause is executed, except exiting loop by "break"

Another useful example covers try-catch-else is at Else Clauses on Loop Statements

沒有留言:

張貼留言