Control Flow in Python

Joseph Mellor
12 min readFeb 16, 2023

To make a program do different things for different inputs, we need loops and branches.

Image made by me using the python logo, cool-retro-term, vim, the onedark color scheme, and GIMP.

In the first article of this series, we set up python for the rest of the series. In the second article, we introduced some fundamental objects and operators on those objects. At this point, we know enough to make working programs, but these programs can only do one thing. To fix the problem, we need to introduce branches, loops, and functions.

Branches allow us to do different things in different scenarios, loops allow us to do the same thing over and over and over again, and functions allow us to greatly simplify our code.

Topics Covered

As always, here are the topics covered. If you know these well, skip this article (and maybe read one of my other articles).

  • Boolean Values: True and False
  • if: (conditional branches/selection statements)
  • for and while: (loops)
  • break and continue
  • List Comprehension
  • range
  • enumerate
  • def: (functions)

On Experimenting

Now that we’re moving onto more complicated materials, it might help to move your experiments in files rather than in the terminal python interpreter. You can create this file in the same directory as word_counter.py in the same exact way as you created word_counter.py. We'll call it example.py. You should put example.py into ~/dev/py_data_vis if you're on Linux or Mac and example.py into C:\Users\[user]\dev\py_data_vis, where [user] is your username. You could put the file in any directory you wanted, but putting it here is easiest.

Making example.py an Executable

Remember that to make a python executable from the terminal, you must make the first line of the file

#!/usr/bin/env python3

and run the commands

user@comp:~/dev/py_data_vis$ ls -l
-rw-r--r-- 1 user group 23 Mar 30 14:52 example.py
-rwxr-xr-x 1 user group 23 Mar 30 14:52…

--

--

Joseph Mellor

BS in Physics, Math, and CS with a minor in High-Performance Computing. You can find all my articles at https://josephmellor.xyz/articles/.