What is Control Flow?

Ordering & Controlling Statements in Code

Things That Flow

A stream flowing towards the sea.
Traffic flow on a busy road.
Conversation flowing between people.

Code Flows Too

  • The flow of code and the steps that impact that flow are called “control flow”.
  • In general code flows in the way same as a book (with some exceptions).
    • Each function is completed before considering the next.
  • Functions can be nested in other functions - the inner most function is completed first.
  • Control structures can be used to change the course of a program.
  • Repetition structures can be used to repeat a section of code.

Control Flow Structure

How to Structure Control Flows in Python

Sequential Structure

  • In general code flows like a book reads:
    • Statements (like lines of code) run top to bottom line,
    • Left to right in statement,
    • Each statement being completed before moving to the next.
v = "2"         #stores "2" as a string in 'v'
i = int(v)      #stores v as an integer 'i'
t = type(i)     #stores the type of 'i' as 't'
print(t)        #prints 't'

Nesting Functions and Operations

  • We are not limited to a single function or operation per row.
  • The previous example could be re-written as:
    • print(type(int("2")))
  • Nesting functions can be useful, however care should be taken and it may be easier to separate functions over multiple rows.

Control Structures

  • Control structures (also known as decision structures) allow the flow to respond to varying situations.
  • A decision is made based on one or more conditions.
  • These control structures are very similar to the IF function in Excel and the CASE statement in SQL (but remember that indentation matters in Python).
Python - Control SQL - CASE Excel - IF
if x = 2: CASE WHEN x > 2 IF(x > 2,
y = 1 THEN 1 1,
else: ELSE
y = 0 0 END 0)

The Importance of Being Boole(an)

  • George Boole was an English Mathmetician and logician whose work on binary logic has resulted in binary conditions bearing his name
  • Any statement that can be evaluated as only either True (1) or False (0) is Boolean.

Repetition Structures

  • Repetition structures (commonly referred to as “loops”) allow for us to recycle chunks of code to perform the same or similar operation a specified number of times or until a condition changes.
  • For loops cycle through a series of iterations, until they reach the end performing each series of statements for each iteration.
    • This can be used to cycle through a list, dictionary or other iterable as well as working through ranges of numbers
  • While loops continue until a predetermined condition changes from True to False.
    • This can be useful for testing conditions but comes with a warning:
  • Make sure your condition will change at some point or else your loop cannot end.

What is Iterability?

  • Iterability is the ability to split an object into discrete items. The item may be ordered or unordered, each item will be extracted, processed ad set aside.

  • In general if an object can be split into multiple items it can be iterated (integers and floats are not iterable).

  • Iterable objects include:

    • Strings (the word “strings” contains 7 iterable items).
    • Lists eg [1, 2, 3, 4, 4, 4, 5, 6]
    • Tuples eg (12, ‘Red’, ‘Apples’)
    • Sets eg {1, 2, 3, 4, 5, 6}
    • Dict eg {ICB_Code: ‘QSL’, Metric_Code: E.M.10}

Code Examples

Code Flow Structures in Action

Sequential Structure Example

  • The following sequential code will create a variable called ‘var’ which is a string, it converts this string to an integer and conducts a series of mathematical operators before printing the result:
var = '22' # set "var" to '22'
var = int(var) # convert "var" to int
var = var  / 2 - 3 # apply math operators
print (var) # print result

Control Structure Example

  • This code checks if a variable called ‘provider’ in this list is equal to a selection of values and prints out an associated string.
if provider == ‘ryr’:
  print(‘SUSSEX’)
elif provider == ‘rhu’:
  print(‘HIOW’)
elif provider == ‘rxq’:
  print(‘BOB’)
else:
  print(‘Unknown’)

Control Structure Example

For comparison, this is the equivalent SQL CASE statement.

CASE
  WHEN provider = 'ryr'
    THEN 'Sussex'
  WHEN provider = 'rhu'
    THEN 'HIOW'
  WHEN provider = 'rhu'
    THEN 'BOB'
  ELSE 'Unknown'
  END

Watch Out for Unintended Consequences

  • Not taking care over your coding can cause big issues. Consider the corner cases and unintended consequences?
  • Empty variables, incorrect data types, and misunderstood flow in the structure can affect your program.
  • Close the loop! Make sure you know how your loops are being switched off and that it’s possible.
  • A cautionary tale: The Virtual Plague That Nearly Wiped Out The World of Warcraft

The “Corrupted Blood” Incident - a fairly famous coding error.

Final Thoughts

  • Don’t worry about memorising any of this!
  • The aim of this session is to give a basic understanding of the logic needed to implement control flow in your program.

Further Reading

Thank You!


Contact:

Code & Slides:


… And don’t forget to give us your feedback.