Branching
Branching
Up until this point, all the programs we’ve seen and written proceed in a linear fashion from beginning to end. This is fine for some programs, but it’s rather inflexible. Sometimes we want our program to respond differently to different conditions.
Imagine we wanted to write a program that calculates someone’s income tax. The US Internal Revenue Service recognizes five different filing statuses:
- single,
- married, filing jointly,
- married, filing separately,
- head of household,
- qualifying widow or widower with dependent child.1
So in writing our program we’d need to prompt the user for different questions, gather different data, perform different calculations, and use different tax tables depending on a user’s filing status. Obviously, this cannot be done in a strictly linear fashion.
Instead, we’d want our program to be able to make decisions, and follow different branches, depending on the results of those decisions.
This example of an income tax program is by no means unusual. In fact, most real-world programs involve some kind of branching.
When our program includes branches, we execute different portions of our program depending on certain conditions. Which conditions might those be? It depends entirely on the program we wish to write.
Thus, most programming languages (Python included) allow for control flow—which includes branching and conditional execution of code.
How do we do this? In Python, we accomplish this with if
, elif
and else
statements (or combinations thereof).
if
, elif
, and else
if
, elif
, and else
work with Boolean expressions to determine which branch (or branches) our program will execute.
Since tax preparation is complicated, let’s consider more modest examples.
Examples using if
, elif
, and else
A minimal program we could write using if
and else
might work like this:
- Prompt the user to guess a magic word.
- If the user guesses correctly, print “You WIN!”
- If the user does not guess correctly, print “You LOSE!”
Let’s think about what we’d need for this program to work:
- A secret word.
- Prompt the user for their guess.
- Then compare the user’s guess with the secret word.
- Print the appropriate message.
Here’s how we can do this in Python using if
and else
.
"""
CS1210
Guess the secret word
"""
= "secret"
secret_word
= input("What do you think the secret word is? ")
user_guess
if user_guess == secret_word:
print("You WIN!")
else:
print("You LOSE!")
Here’s another example, but this time we’re using a nested if
statement and an elif
(which is a portmanteau of “else” and “if”):
"""
CS 1210
What's for dinner?
"""
= float(input('What is your bank balance $? '))
bank_balance
if bank_balance < 20.0:
= input('Do you have any meal points? y/n: ')
meal_points if meal_points == 'y':
print('Eat at the dining hall.')
else:
print('Eat that leftover burrito.')
elif bank_balance < 50.0:
print('Order pizza from Leonardo\'s')
else:
print('Go out to Tiny Thai in Winooski with a friend!')
First we prompt the user for their bank balance. If this amount is less than $20.00 then we prompt the user again to find out if they have any meal points left. If they do, that is, if meal_points == 'y'
, we print “Eat at the dining hall.” If not, we print “Eat that leftover burrito.”
Now, what happens if that very first condition is false? If that’s false, we know we have more than $20.00, so our next comparison is:
elif bank_balance < 50.0:
Why not
elif bank_balance >= 20 and bank_balance < 50.0:
you might ask? Because we only reach the elif
if the first condition is false. There’s no need to check again.
So if the bank balance is greater than or equal to $20.00 and less than $50.00 we print “Order pizza from Leonardo’s”.
Now, what if the bank balance is greater than or equal to $50.00? We print “Go out to Tiny Thai in Winooski with a friend!”.
We can have a single if
statement, without elif
or else
. We can also, as we’ve just seen, write compound statements which combine if
and else
, if
and elif
, or all three, if
, elif
, and else
. We refer to each block of code in such compound statements as clauses (distinct from clauses in a compound Boolean expression).
Some important things to keep in mind
If we have a compound if/else statement in our program either the body of the
if
clause is executed or the body of theelse
clause is executed—never both.If we have a compound if/elif/else statement in our program, the body of only one of the branches is executed.
Supplemental resources
For more on control of flow, see:
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.
Footnotes
Discussion of the fairness or consequences of such a classification is outside the scope of this text—a state of affairs that suits this author just fine.↩︎