top of page

07.07.2018: One Lesson of Python

Today's soundtrack is Katatonia: Dead End Kings.

This morning, I'm working on the second chapter of Al Sweigart's Automate the Boring Stuff With Python, "Flow Control."

We use "[f]low control statements [to] decide which Python instructions to execute under which conditions" (citation). This idea works just like a flowchart. See the Engineering Flowchart, created by Reddit user neotecha.

We use Boolean values (True and False) "to represent those yes and no options" (citation). To determine whether a scenario is true or false in our Boolean value, we use "[c]omparison operators [to] compare two values" (citation).

There are six comparison operators that we use in Python: "== Equal to[,] != Not equal to[,] < Less than, > greater than[,] <= Less than or equal to[, and] >= Greater than or equal to" (citation).

We use "the three Boolean operators (and, or and not)" (citation, - bold text mine) to compare our Boolean values; these have a hierarchy: "Python evaluates the not operators first, then the and operators, and then the or operators" (citation).

There are three flow control statements: "if, elif, and else" (citation). We use "if" to start a conditional command. We use "elif" to give other possible scenarios. If none of the foreseen scenarios plays out, we use "else" to tell the program what to do if none of the conditions are met. For example, I could program a loop saying "if variable x is less than fifteen, print a statement saying that there are still some oranges left, and add a value of 1 to variable x at the end of each loop, else print a statement saying that there are no oranges left."

We can tell the program to execute a block of code repeatedly while a condition is true by using "the while keyword" (citation). We can end the loop by either having the program reach a point where the condition is no longer true, or by entering the break command. If we have several conditions that must be met before moving on to the next ones, we can use the continue statement to make it so that the next block of code will be executed once the preceding value is true.

One useful trick, rather than writing elif statements for every possible number in a range, is to use "[t]he range() function" (citation). Inside of the range brackets, we can use either two or three commands: If I say range(20, 41), the program will look for any numbers between 20 and 40. If I say range(0, 31, 5) the program will count by fives from 0 to 30.

If we don't want to wait for the program to reach the end of its code before it exits, we can use the "sys.exit()" command after importing the sys module, "since this function is in the sys module" (citation).


bottom of page