Skip to content

Python Course – 4. Flow Control Structures

Learn Python flow control: if conditionals, for and while loops, and scope, with theory, videos and exercises to practice making your code take decisions.

Make decisions, give your data some intelligence so actions happen automatically, like raising the temperature if it’s cold or lowering it if it’s hot, or writing a sentence a million times with just two lines.

Theory

Skip to PDF content

4.1- If – Conditional Statement

I want an ice cream. Which path should I take? The one that leads to the ice cream shop, or the one that leads to everything else? It’s a simple decision, but you have to make it correctly, and think about it however little; otherwise, we’ll end up somewhere else that isn’t our goal.

4.2- If – Conditional Statement – Scope

The scope of the code limits which lines of code will be executed depending on which path is taken. It depends on the body being executed.

4.3- Example – If – Conditional Statement

A quick example of a conditional statement with real, working code.

4.4- For Loop

Write something once, then the same thing again, and once more exactly the same. Why repeat the code if it can repeat itself as many times as we want?

4.5- For Loop – Basic Body Scope

The code that will be repeated inside a for loop and the code that will NOT be repeated.

4.6- Example – For Loop – Basic Body Scope

An example with for loop code to clearly tell its scope apart.

4.7- For Loop – Loop Control

A for loop can run a million times, but what if we want to end it earlier? Do we wait for the million iterations to finish? Or do we control it so it ends whenever we want?

4.8- For Loop – Scope of Multiple Bodies

The scope of one body can sit inside another body that in turn has its own scope.

4.9- Example – For Loop – Scope of Multiple Bodies

An example of how several for loops are used and how each one affects each of the bodies.

4.10- While – Conditional Loop

A for loop can be controlled with break and finally, but it isn’t elegant. Wouldn’t it be ideal to have the best of the for loop and the if conditional in a single structure? Well, it’s called the While loop.

4.11- While – Scope of the Conditional Loop

Since the while loop is a mix between the for loop and the if conditional, its scope varies slightly.

4.12- Example – While

Example of using the While loop.

Exercises

Exercise 4.1-pan_y_chocolate.py

Create a program that asks via the keyboard (hint: input) whether there is “chocolate” first and whether there is “flour” afterwards (hint: bool(“Any value”) is True, or bool(“”) is False).

If both are true, we’ll print “Let’s bake a cake”

If only “chocolate” is true, we’ll print “We’ll make chocolates”

If only “flour” is true, we’ll print “We’ll bake bread”

If neither is true, we’ll print “Today I rest”

Console output of the exercise: asks about chocolate and flour, and since only flour is available it prints "Hornearemos pan"

Exercise 4.2-tablas_de_la_verdad.py

Create a program that builds the AND and OR truth tables.

To do so, use two variables “a” and “b” that get updated on each iteration of a “while” loop, which ends after “a” and “b” are both False (hint: start by programming the AND table, and then continue with the OR table using a helper variable “ultima_iteracion”).

And print the result of each iteration in a readable format like this (the spacing doesn’t need to be perfect, although tabbing with \t can help):

Truth table of the OR operator with the four combinations of A and B; only False or False gives False

Exercise 4.3-base_de_datos_banco.py

We work for a bank and we have to create a database to store our users’ money. The program will ask us forever (hint: while true) for the user’s name (key) and then a positive or negative amount of money (a numeric value; value). If the user already exists, we’ll have to add the newly entered money to whatever they already had; if they don’t exist, we’ll simply store it.

We can print the dictionary on each iteration to see what we’ve entered and what has been updated.

Console output of the bank exercise: the dictionary of users and money is updated, with Juan going from 100 to 70

Exercise 4.4.-diccionario_seleccion_futbol.py

Given the following list representing the players of the Spanish national football team that played the 2010 World Cup:

futbolistas = ["1 - Casillas", "15 - Ramos", "3 - Pique", "5 - Puyol",
               "11 - Capdevila", "14 - Xabi Alonso", "16 - Busquets",
               "8 - Xavi Hernandez", "18 - Pedrito", "6 - Iniesta",
               "7 - Villa"]

You are asked to:

  1. Going through the list only once, add to another dictionary called “pares” the players whose key is even
    (key: jersey number, value: name), and to a list called “impares” the names of the players whose key is odd.
  2. Sort the “impares” list alphabetically.
  3. Given the “pares” dictionary, create another dictionary “pares_al_reves” that has the player’s name as the key and
    the player’s jersey number as the value.

“Python Course – 4. Flow Control Structures” by Ramón Invarato at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

Ramón Invarato

I design and build data platforms and intelligent systems, and I enjoy sharing that experience here.

You may also like

Comments

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.