Control flow tools is something I've always been really bad at beyond the basic loops and if-else statements. Or actually something I've never really known what was. But today as I was prototyping a script, I wanted to write up some program structure, and got hit hard in the head with the importance of understanding some of the “exotic” control flow tools.
if inpt == ' ': #initialize splitting of current word if inpt == 'redo': #initialize code for resplitting entire tweet if inpt.upper() in tags: saveline(w+sep+inpt.upper(), f) if inpt = 'quit': quit()
Will give you a very hard to understand error
File "", line 3 if inpt == 'redo': ^ IndentationError: expected an indented block</pre>
But my indentations are okay!
pass is a control flow tool that can stand in for nothing. Python expects something after an
if-statement, so in the above example it assumes the following
if-statement is nested, but since it hasn't been indented probably, Python throws an error.
pass tells Python that this too, shall pass.
def thistooshallpass(): pass
won't throw any errors, and let you place functions and other structures in-place in your code, waiting to be filled with actual instructions, once future you gets off your lazy bum.
Break & Continue
These are pretty cool too.
Break stops a
while-loop prematurely, while
continue jumps back to the next iteration of a
for or a
In : a = 0 In : while True: ...: break ...: a += 1 ...: print a ...: 0
a never grows, because the
break construct broke out of the
while-loop (and saved us from an indefinite loop too!)
In : for i in range(10): ...: if i < 5: ...: continue ...: break ...: print i ...: 5
break statement is not reached while
i < 5, but once it hit 5, the
continue statement is no longer executed and the interpreter reaches the
break statement and terminates the loop, thus giving us a nice 5.
- See more here: http://docs.python.org/2/tutorial/controlflow.html
- And this guy has a great use of brake and continue to build a construct that let's you break out of nested loops: http://stackoverflow.com/a/654002