Chapter 4Control Flow and Loops
When writing Excel formulas, you often want some action to be taken only if a certain condition is true.
This idea of conditional action is so common that Microsoft Excel offers many functions that perform conditional actions.
Some examples:
IF()IFS()SWITCH()SUMIF()SUMIFS()COUNTIF()COUNTIFS()
And the list goes on!
Just as it’s common to use conditional formulas in Excel, you also need your Python formulas to run code when certain conditions are true.
In this chapter you learn how to control the flow of your Python code, including having your Python code run many times if needed.
4.1 if/else STATEMENTS
Arguably the most used Excel conditional function is IF(). Over the years, I’ve seen Excel formulas like the one in Figure 4.1 many times.

Figure 4-1: Conditional Logic in Excel.
Notice how the formula in Figure 4.1 uses nested calls to IF()? This is known as conditional logic. Conditional logic is so useful that programming languages have the equivalent of Excel’s IF() function.
Python is no exception.
4.1.1 Basic if
You use Python’s if statement when you want some of your code to be run only when some condition is True. While this is a contrived example, the code in Figure 4.2 illustrates the how and why of using if.

Figure 4-2: An ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access