PYTHON BASICS
Python Basics: Conditional Statements
Control Flow — Part 1
In Relational Operations and Logical Operations, we took a deeper look at the Boolean data type, and the operations that can be applied to it. Just as arithmetic operators ( + — * / ) are crucial for any meaningful computation with numbers, these operators are the essential building blocks for working with Boolean values.
But so far, the Python programs we’ve been developing have not been particularly useful. Although we were able to compute the number of weeks in a year, and also determine whether to wear a sweater depending on the outdoor temperature, we can already calculate these values easily without the need of a computer program.
These are simple programs that we as humans can easily perform ourselves. The real power of computer programming lies in the ability to control the sequence of steps that a program takes to accomplish a task.
Recall that programming languages allow us to list out a sequence of actions we want the computer to perform.
a = 2 + 2 # 1. Create a variable a containing the result of 2 + 2
b = a * 3 # 2. Create a variable b containing the result of a * 3
c = b - a # 3. Create a variable c containing the result of b - a
print(c) # 4. Output the value of the variable cWhat if we want the flexibility of choosing only one of two actions to perform? For example, to output the string "Adult" if the age variable is 18+, or output "Not Adult" otherwise.
age = 17 # 1. Create a variable age containing 17
... # 2a. Output "Adult" if age is greater than or equal 18
... # 2b. Output "Not Adult" if age is less than 18How could we write a computer program that would choose the appropriate action to perform? The solution is conditional statements.
Control Flow
In computer science, control flow (or flow of control) is the order in which individual statements, instructions … are executed or evaluated. — Wikipedia
The programs we’ve been writing up to this point have been rather sequential, in the sense that Python always executes the statement in each line, proceeds to the next and executes that, and so on.
a = 2 + 2 # runs first
b = a * 3 # runs second
c = b - a # runs thirdWhile this is good enough for the programs we’ve written so far, we later encounter a roadblock when we need our programs to perform more complex tasks.
Age Group Classification
Suppose we want a computer program that will determine a person’s age group based on their age.
0-12 Child
13-17 Teen
18-24 Youth
25-64 Adult
65+ SeniorEssentially, what we want is for the computer to choose the appropriate string to output based on the age provided. And unlike the Fahrenheit example, there is no one-shot mathematical formula we can apply to solve this problem.
age = ... # replace with your age
print("Child")
print("Teen")
print("Youth")
print("Adult")
print("Senior")This code example will be executed line-by-line by the Python interpreter with the following output, whereas we want the output to be only one of the groups.
Child
Teen
Youth
Adult
SeniorIf only we had a way to tell Python which line to execute, and which to ignore. But first, let’s visualize the order in which this program executes.
1. Create a variable `age` that stores an individual's age
2. Output "Child"
3. Output "Teen"
4. Output "Youth"
5. Output "Adult"
6. Output "Senior"Initially the program creates a variable age. Then it proceeds to output "Child", then "Teen", then "Youth", then "Adult", and finally "Senior".
Get Gideon Oludeyi’s stories in your inbox
Join Medium for free to get updates from this writer.
But this is not the program we want. We want to output only one of those age groups. We want a program that looks like the following.
1. Create a variable `age` that stores an individual's age
2. Output "Child" if the `age` is between 0 and 12
3. Output "Teen" if the `age` is between 13 and 17
4. Output "Youth" if the `age` is between 18 and 24
5. Output "Adult" if the `age` is between 25 and 64
6. Output "Senior" if the `age` is 65 or moreLike the previous diagram, we initially create the age variable. But now we perform a comparison on the age, and based on the condition it satisfies, we execute the corresponding statement. For example, if age = 10, then we only execute #2 because 10 is between 0 and 12. Whereas if age = 33, then we only execute #5 because 33 is between 25 and 64, and all other conditions are False.
This is the essence of a conditional statement. We decide which statement gets executed based on the conditions we supply, and all other cases are ignored.
Think of a railroad with a set of tracks. A single track is like a sequential flow of execution where the Python interpreter executes one line after another, just as we’ve always been doing. But conditional statements are the switches that change which track the train runs on.
If Statement
The if-statement is the common structure for using the conditional statement. It allows the program to choose one of multiple code blocks to execute based on whichever satisfies a given condition.
Syntax
if <CONDITION_1>:
... # runs if <CONDITION_1> is True
elif <CONDITION_2>:
... # runs if <CONDITION_1> is False, but <CONDITION_2> is True
elif <CONDITION_3>:
... # runs if the above conditions are False, but <CONDITION_3> is True
else:
... # runs if all the conditions above are FalseUsage
age = ... # replace with your age
if age >= 0 and age <= 12:
print("Child")
elif age >= 13 and age <= 17:
print("Teen")
elif age >= 18 and age <= 24:
print("Youth")
elif age >= 25 and age <= 64:
print("Adult")
elif age >= 65:
print("Senior")
else:
print("Invalid age") # runs only if age < 0 (negative)For an if-statement, the condition specified has to evaluate to a Boolean value. The corresponding code in its indentation block is executed only if the condition is True.
Indentation Block
Now would be a good time to talk about indentation blocks in Python.
Unlike most programming languages, Python relies extensively on indentation to understand whether a statement is part of a conditional. Think of it as the grammar rules for the Python language. It wouldn’t be valid Python if these rules were violated.
condition = ... # replace with a Boolean value
if condition:
print("This line is run only if `condition` is true")
print("This line is also run only if `condition` is true")
print("This line runs regardless")The first two print statements are under the if-statement because of the indentation, therefore, Python understands to only execute those lines only if condition is True. On the other hand, the third print statement will always execute because it’s not part of the if-statement.
Elif
The elif clause is an optional feature to specify other cases of the if-statement.
Python starts with the if clause to determine whether the condition specified is True. If that condition is True, then Python executes the corresponding code block, ignoring the subsequent clauses. However, if the condition in the if clause is False, it proceeds to next elif clause and repeats the same process.
You can have as many elif clauses as you need (0+), but they have to be placed between the if and else clauses.
number = 4
if number < 10:
print("Ones")
elif number < 20:
print("Tens")
elif number < 30:
print("Twenties")Although the conditions in the if-statement above are all True, Python only executes the first clause whose condition is True, ignoring the subsequent clauses. That’s why the output for this code is "Ones".
If number was 14, then the output would have been "Tens" because the first condition to evaluate to True would be number < 20.
Else
The else clause is also an optional feature of the if-statement that acts as the last resort when all the conditions have failed.
It is not mandatory to include an else clause, but it must be the last clause in the if-statement when included.
number = 0
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")In this example, the else clause will be executed because all the previous conditions evaluate to False. Omitting the else clause means that there’d be no output if number was 0.
Conclusion
By default, Python programs are executed sequentially (line-by-line). But we were able to change this behavior in order to select which statements get executed and which get ignored using the if-statement. This idea of selection is one of the three fundamental structures that power most computer programming languages today: Sequence, Selection, and Iteration.
In the next article, we’ll be looking at another type of conditional statement that enable computer programs to repeat a series of actions while a given condition is satisfied.





