This is a cheat sheet for standard flow control in Python. It's an example of all items listed in Essential Interview Code for Flow Control. Knowing this, or having the list handy, will speed you along in coding interviews.
These examples are written with type annotations, which are optional, though recommended, in Python.
# Function without return def say_hello() -> None: print("hello") say_hello() # Function with return def add( a : int, b : int ) -> int: return a + b print( add( 3, 5 ) ) # Multiple return values def multi_value() -> Tuple[int,str]: return (5, "hello") (count, text) = multi_value() # Return (and previous examples) def early_return( cond : bool ) -> None: if cond: return print( "Good" ) # Implicit Returns (offered in lambas) mul_10 = lambda x: x * 10 print( mul_10(5) )
# if if a > 5: print( "High" ) # if-else if a > 5: print( "High" ) else: print( "Low" ) # if-else chain if a > 5: print( "High" ) elif a == 4: print( "Mid" ) else: print( "Low" ) # switch if value == "apple": print( "Crunchy" ) elif value == "orange" or value == "grape": print( "Juicy" ) elif value == "avacado": print( "Smooth" ) else: print( "Food?" )
# Count loop for i in range(10): print(i) # While loop while random.random() > 0.2: print(".") # Collection loop items = [ 3, 6, 8, 11, 13 ] for item in items: print( item ) # Break for item in items: if item > 7: break print( item ) # Next/Continue for item in items: if item == 8: continue print( item ) # Infinite loop while True: c = random.random() if c < 0.1: break if c > 0.5: continue print( c )
# Raise def broken() -> None: raise Exception( "broken-not-working" ) # Propagate def pass_thru() -> None: broken() # Catch def handle_it() -> None: try: pass_thru() print( "unreachable" ) except Exception as e: print( "caught", e ) # Resume def note_it() -> None: try: pass_thru() print( "unreachable" ) except Exception as e: print( "allowing", e ) raise
Not all languages will contain all of the below mechanisms. You should nonetheless know the purpose of each and how to achieve it.
# Finally def maybe() -> None: if random.random() < 0.5: raise Exception( "maybe-not-working" ) def test_finally() -> None: try: maybe() print( "maybe" ) finally: print( "always-cleanup" ) # With with open( "file.txt", "w" ) as f: f.write( "hello" )
Defer / Custom
There is no standard defer flow in Python and you should use a combination of finally and maybe. This example show a way to mimic defer flow using a custom with flow class.
class Defer: def __init__(self): self.actions : List[Callable] =  def __enter__(self): return self.actions def __exit__(self, type, value, traceback): for action in self.actions: action() def defer_like() -> None: with Defer() as defer: a = 5 defer.append( lambda : print( "cleanup", a ) ) maybe() a = 4 defer.append( lambda : print( "last-defer" ) ) maybe() a = 3 try: defer_like() except: print( "!" )