Control flow

Posted on Thu 19 December 2013 in Notes

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[0] == ' ':
    #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

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 for or while-loop prematurely, while continue jumps back to the next iteration of a for or a while-loop.

In [7]: a = 0

In [8]: 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 [9]: for i in range(10):
   ...:         if i &lt; 5:
   ...:                 continue
   ...:         break
   ...: print i
   ...: 
5

Here the 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.