# Chapter 4 - Control Flow

## 4.1 - Booleans

Important Note:

Now would be a good time to read about logic in chapter 24.1. In that chapter I introduce mathematical logic, in particular, truth tables. You will need to have a solid understanding of truth tables in order to make the most of this chapter. Having a clear understanding of this section of logic will also help you get rid of some weird bugs in your programs further down the line.

If you can remember back to the example of making a cup of tea, we had a step that went something like:

- if want milk:
- take milk from fidge
- pour milk

The above snippet allowed us to make a decision. In programming this construct is called control flow. We either wanted milk or we didn't. In order to implement this kind of thing in our programs we need to introduce a new type called the bool which is short for boolean.

A boolean is a type which has two values: true or false.

python >>> type(True) <class 'bool'>

type(False) <class 'bool'> 

This brings me to an important point. In Python, different values of different types can be truthy or falsey.

For example, with integers, 0 is falsey while any other integer is truthy. With floats, 0.0 is falsey while any other float is truthy and finally with strings, the empty string ('') is falsey while any other string is truthy.

>>> False == 0
True
>>> False == 1
False
>>> False == 0
True
>>> False == 0.1
False

We can also cast any other value to a bool using the bool() function if the value can be interpreted as a truth value.

Booleans also have operators. These are different to the operators we've seen with integers and floats. These are boolean operators. The following tables will be explained fully in chapter 24.1.

OR Truth Table

P Q P OR Q
True True True
True False True
False True True
False False False

AND Truth Table

P Q P AND Q
True True True
True False False
False True False
False False False

NOT Truth Table

P NOT P
True False
False True

Here are a few examples in Python

>>> True or True
True
>>> True or False
True
>>> False or False
False
>>> True and True
True
>>> True and False
False
>>> not True
False
>>> not False
True

Again, knowing these truth tables off like the back of your hand is crucial. You'll be dealing with these a lot!

## 4.2 - The if Statement

In this section we're going to look at adding control flow to our programs. We'll start by looking at the if statement. Before we do though, I want to look at something called comparison operators. These operators allow us to compare things.

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

They're pretty simple to understand so let's take a look at them in action:

>>> 1 == 1
True
>>> 1 == 2
False
>>> 10 != 4
True
>>> 4 != 4
False
>>> 11 > 9
True
>>> 13 < 23
True
>>> 16 < 2
False
>>> 13 < 13
False
>>> 13 <= 13
True

I think you get the gist. So let's get onto the if statement.

wants_drink = input("Do you want a drink with your meal? (yes or no): ")
if wants_drink == "yes":
print("That will cost an extra £1.50")
print("Thank you! Enjoy your meal")

If we run the above code with two different types of input we can get two different results:

# USER ANSWERS YES
Do you want a drink with your meal? (yes or no): yes
That will cost an extra £1.50

Do you want a drink with your meal? (yes or no): no
Thank you! Enjoy your meal

The above code reads quite clearly as well, almost like English. If the user says yes to wanting a drink then print that it will cost more.

The syntax for if statements is as follows:

if <CONDITION>:
# Do something if condition evaluates to True

A couple of important things to note on the syntax. It is always if followed by the condition, then a colon (:). For the block of code that follows, it must be indented!! I like to use tabs however you can use spaces. Right now I'm going to tell you to pick a number of spaces. It's typical to use 4 spaces. For tabs, 1 tab will suffice.

Let's look at another example:

my_number = int(input("Enter a number: "))
if my_number <= 10:
print("First line")
print("Second line")
my_float = 4.3
print("Goodbye")

The above program does nothing useful, in fact it's complete garbage but it shows the syntax for if statements quite well.

Anything that is indented after the if statement is called a code block. Everything after the if statement such as the my_float = 4.3, will be executed regardless of my_number being less than or equal to 10.

You'll probably make a lot of syntax mistakes in the beginning, we all did so don't let that discourage you at all, it's completely normal. Even the most experienced developers make syntax mistakes every now and again.

Although the if statement is useful, what if we're in a situation where wanted to do one thing if one condition passed, otherwise, do something else? Next we're going to look at the if-else statement.

## 4.3 - The if-else statement

In the previous section we learned how to add some very basic flow control to our program however we imagined a scenario in which we wanted to do something else if the condition for the if statement didn't pass.

Let's look at how to do that:

my_age = int(input("Enter your age: "))

if my_age >= 18:
print("You can enter")
else:
print("You are too young to enter")

print("Goodbye")

It again, is quite easy to read the above program. When we execute the above program we could have two different outputs:

# SCENARIO 1
You can enter
Goodbye

# SCENARIO 2
You are too young to enter
Goodbye

The syntax again is quite obvious:

if <CONDITION>:
# Do something if the condition was True
else:
# Do something else!

REMEMBER:

Don't forget the colon at the end of each statement and don't forget to indent the code block. Each statement in the code block must also be indented the same number of spaces!

Let's look at another example. In this example we want to write a program that will tell us if an integer is even or odd:

number = int(input("Enter a number: "))
if (number % 2) == 0:
else:
print("Your number was odd")

Remember back to the chapter on integers, we had the modulus (%) operator? To refresh your memory, this operator returned the remainder after division.

The == comparison operator takes two operands, in the above case the left operand was an expression. This will evaluate to a value which is then checked to see if it is equal to zero. If it is, then it is an even number.

We can also combine comparison operators and boolean operators, let's look at an example of how this is done:

number = int(input("Enter an even number between 50 and 100: "))
if (number % 2) == 0 and number < 100 and number > 50:
print("You've entered an even number between 50 and 100")
else:
print("I don't care about your number")

The condition might look nasty but it actually reads quite easily:

"if the number is even AND the number is less than 100 AND the number is greater than 50"

We can even simplify it a bit. Remember I told you that values could be truthy or falsey? Well lets look at our even number program again.

...

if (number % 2) != 0:
else:

...

Note that we are saying if the remainder doesn't equal zero in the condition.

We could simplify this to:

if number % 2:
else:
print("Your number was even")

If number % 2 is 0, then we don't enter the code block for if because 0 is falsey.

REMEMBER: We execute the statements inside the if block only if the condition evaluates to True. Also just to note, else doesn't take a condition. It automatically executes if the condition on the if statement fails.

## 4.4 - The elif statement

Our programs are now getting a little more complex and we have some decent control flow but they're acting as if there's only two options. What if there were 3 or more choices? The elif statement can solve this for us!

The elif statement allows us to check multiple expressions. if...elif...else statements are check in sequential order, evaluating each condition and executes the code block for the first condition that evaluates to true.

The syntax is as follows:

if <condition 1>:
# Do something
elif <condition 2>:
# Do something else
elif <condition 3>:
# Do something else
.
.
.
elif <condition N>:
# Do something else
else:
# Do something else

We can have as many elif statements as we please.

Let's write a program that calculates the grade of a student based on their mark:

mark = int(input("Enter a mark: "))

if mark >= 70:
print("You got a first")
elif mark >= 50 and mark < 70:
print("You got a second")
elif mark >= 40 and mark < 50:
print("You got a third")
else:
print("You failed!")

These elif statements are pretty straight forward.

If you are coming from another language, Python does not provide switch/case statements as do other languages but we can use if...elif...else to mimic them.

## 4.5 - Nested if statements

What if we have a condition and based on that condition we need to check other conditions? Well we can do that by nesting if...elif...else statements inside other if...elif...else statements.

Let's look at an example program to convert the numbers between 0 and 3 to their word equivalents:

number = int(input("Enter a positive number: "))

if number >= 0:
if number == 0:
print("Zero")
elif number == 1:
print("One")
elif number == 2:
print("Two")
elif number == 3:
print("Three")
else:
print("You entered a number greather than three")
else:
print("You entered a negative number")


This is a toy example but nested if...elif...else statements are used everywhere and you'll come across them frequently so spend time becoming familiar with writing them!

They're also quite straight forward so I'm going to get straight into some exercises so you can practice these things.

## 4.6 - Exercises

Important Note:

The solutions to some of these exercises require thinking outside-the-box. Don't expect to arrive at a solution immediately!

### Question 1

Write a program that takes three inputs, a, b and c and prints out whether or not those numbers form a right angled triangle. The formula you'll need is $c = \sqrt ( a^2 + b^2)$

### Question 2

Fizz buzz is a game in which the following rules apply:

• any number which is divisible by 3 is replaced with fizz
• any number which is divisible by 5 is replaced with buzz
• any number which is divisible by both 3 and 5 is replaced with fizz-buzz
• any other number is just the number itself

Examples:

1 = 1
2 = 2
3 = fizz
4 = 4
5 = buzz
6 = 6
.
.
15 = fizz-buzz
###### * Remember what I said about how if...elif..else statements are evaluated sequentially (first to last) until the first condition passes

In your solution you should expect the user to enter a single number and either print the number, fizz, buzz or fizz-buzz

### Question 3

Write a program which takes in six numbers, x1, y1, r1 and x2, y2, r2 (which are the x and y coordinates of the center of a circle and that circles radius) and print out whether or not the two circles overlap.

You're going to need the formula for the distance between two points to solve this which is: $d(P, Q) = \sqrt ((x2 - x1)^2 + (y2 - y1)^2))$ The rest requires some problem solving! Perhaps drawing out the scenario on paper might help?

#### Help support the author by donating or purchasing a copy of the book (not available yet)

Previous Chapter - Next Chapter