Automate the Boring Stuff with Python – Chapter 2: Flow Control

automate (ch2)

Chapter 2 of Automate the Boring Stuff with Python is about flow control, which is basically decision-making in a program. Without flow control, when a program executes, it would run every command in its code, sequentially, until it reaches the end. Depending on the application, this could prove useless or even detrimental to the user. Flow control changes this so that intelligent or user-directed commands are executed instead, allowing programs to react to user requests or other environmental factors. To use a book analogy, its the difference between a traditional story and a choose-your-own-adventure book.

flowchart exPictorially, flow – which is essentially the steps of any process – can be represented with a flow chart. This can visually present starting and stopping points, branching points and other information and is a strong tool for mapping out the logic of a sequence of events on a high level. Programmatically, flow is represented by conditions and controlled by acting on the values of variables at key junctures – namely, the aforementioned branching points.

Boolean values and Comparison operators

Boolean variables can have only one of two values: “True” or “False”. Other data types (integers, floating point numbers and strings) can have a much wider range of values, but are often also evaluated down to a True or False value in order to execute a section of code.

Comparison operators are functions that look at the value of two values and determine whether or not they are equivalent. They use the following logical comparisons to return a True or False value after comparing two values:

Operator     Meaning
==           Equal to
!=           Not equal to
<            Less than
>            Greater than
<=           Less than or equal to
>=           Greater than or equal to

Boolean operators compare Boolean values. There are three of them: and, or and not. They follow truth table logic – remember that from 7th grade math?

The "AND" Operator         The "OR" Operator        The "NOT" Operator
True and True = True       True or True = True      not True = False
True and False = False     True or False = True     not False = True
False and True = False     False or True = True
False and False = False    False or False = False

Boolean and comparison operators can be mixed together to create logic that essentially performs mathematical comparisons of values, evaluates them to true or false values and returns a single True or False value which can then be acted upon.

A brief example of this from the book is: (4 < 5) and (5 <  6) which evaluates to True and True, and then resolves to True.

Conditions

A condition is a more precise name for an expression and is mainly used in reference to flow control statements. Conditions evaluate down to Boolean values – either True or False. Based on this value, the flow control statement determines how a program should proceed. Essentially, the flow control statement is a branching statement or a decision point and the Boolean value passed to it tells it whether to turn right or turn left in its code.

Flow Control

Lines of code meant to work together can be grouped into units called blocks. Blocks begin with a condition and are followed by indented lines of code. They can be nested, which means that a block can contain other blocks – the indentation denotes what level of the nested blocks a given line of code falls in. Its different from other languages that I’ve seen in which indentations are visually helpful for humans to read code more easily, but not a mandatory aspect of formatting in the language. In Python, indentations mean something. I received errors when I tried typing blocks without indenting the right lines beneath an opening line of code.

spam=0
print('Enter 1, 2 or 3')
spam=input()

if spam=='1':
    print('Hello')
elif spam=='2':
    print('Howdy')
elif spam=='3':
    print('Greetings')
else:
    print('Hi')

If/Else statements, While loops and For loops

The three most common types of flow control statements are If/Else statements, While loops and For loops. All three read like English and follow a straightforward logic:

  • If statements: If a condition is true, execute the block of code that follows.
    • If statements can be followed by an “else” statement, which gives a block of code to execute in the even that the If statement is false: If a condition is true, execute the block of code that follows, else execute this other block of code.
    • Elif statements allow more than one else statement to be offered as an option in the event that an if statement is false. (If a condition is true, execute the block of code that follows, else if this other condition is true, execute this block of code, else if yet another condition is true, execute this block of code, etc.)
  • While loops: While a condition is true, keep executing the block of code that follows. (While food remains on my plate, keep eating it.)
  • For loops: For loops execute a block of code a specific number of times. For example, if you’re lonely, you can run this code:
print('Say her name:')
for summoning in range(3):
    print('Bloody Mary')

Other stuff

The last part of the chapter deals with importing modules into Python. Modules are essentially files with additional functions in them that can be used to extend the commands/functions available when writing code. There are many modules available online already, and users can create their own as well. I’ll get into this at a later time, because its more focused on loading files and calling commands from those files than flow control.

Videos 4 & 5 in Al Sweigart’s tutorial on YouTube cover topics in chapter 2. They can be found here:

Lesson 4 (flow charts, boolean values, comparison operators, and boolean operators):

Lesson 5 (if, elif, and else flow control statements):

Leave a comment