In our everyday lives, we rarely follow a linear course of action regardless of what may arise. Instead, we often make choices based on the information at our disposal.
For example, we may plan to go running, but if we step outside and it’s snowing, we may choose to go make snow angels instead. Python mimics this real-life decision-making process in the form of conditionality — by which code blocks are executed only upon the meeting of predefined conditions.
In this article, we’ll define control flow, look at how Python conditionality is evaluated and go over practical examples of using conditional statements in Python.
What is Control Flow?
Novice developers typically first learn about sequential execution, in which code executes one line after the next, without skipping statements, and referencing earlier definitions or looping over multiple statements repetitively. But frequently, a program needs to do just that to respond appropriately to real-life input or to simulate everyday events.
The flow of execution that determines which code to run is referred to as control structure. Conditionality, loops, and some functions break sequential execution, and thus manage control flow. The program flow changes from its default of sequential logic to iteration logic (also called repetitive flow) when it encounters a loop, and to selection logic (conditional flow) when a decision needs to be made. In this article, we’ll explore the conditionality aspect of control flow.
A note before we proceed: The use of exceptions for flow control is frequently a point of contention for beginner programmers. Exceptions are not a flow control mechanism, but rather an error handling mechanism:
As you can see, exceptions are meant to catch errors when they occur and notify the user, rather than provide an alternate conditional statement.
For more about control flow, we recommend checking out the official Python docs. Now, let’s explore more about conditional statements in Python.
Conditionality in Python
The Python if statement is at the heart of the language’s conditionality:
Here, the <expression> evaluates to a boolean. If that boolean is true , the <statement>, which must be a valid, properly-indented Python statement, will run. Notably, in following a convention known as the off-side rule, Python uses leading indentation to denote code blocks. You must indent after any conditional expression for the language to execute the subsequent statement. Here’s an example:
Let’s say we want to give the program other options. When it snows, we’ll want to make snow angels, but does that mean we’ll want to do nothing when it doesn’t snow? Certainly not! To give the program choices, we use the elif and else keywords. Let’s first focus on else, because when there are only two choices, the statement following the else clause will provide the alternative choice:
If <expression> is true, the first block runs and the program skips the second one. If <expression> is false, the program skips the first block and executes the second one. In other words, a Python if-elif-else statement is designed to only recognize one truthy expression.
Once the program evaluates the expression(s) and runs the statement associated with the truthy evaluation, it will revert back to its default of sequential execution.
When you have three or more alternatives, the elif (short for else if) clause provides syntax for even more branches of possible execution. Python sequentially looks at each expression and runs the statement corresponding to the first truthy expression. If no expressions evaluate to true, it will run the statement associated with the else keyword.
Unlike the else clause, there’s no limit to the number of elif clauses you can add. Remember that just as the else is always optional, so too is the elif; but if you’re using both, the single else clause must always follow all elif clauses. It’s best practice to end with an else clause if you do include one or more elif clause.
Recall that only one specified code block will run in the context of Python conditionality. So if multiple conditions do evaluate to true, Python will only evaluate the first, run its block and then skip all other clauses in the extended if statement. To illustrate this using our example:
This happens because Python uses something called short-circuit evaluation when executing if statements with elif clauses: once the program determines one of the expressions to be truthy, it won’t even test any of the remaining expressions.
Alternatively, if all expressions evaluate to “false” and an else clause isn’t specified, the program will not execute any code blocks. In this example, nothing will print:
Now let’s take a look at operators, which help the program understand which code blocks to execute.
Operators play an important role in Python conditionality: They evaluate if an expression is true or false. There are many types of operators, as illustrated by this w3schools description. Mathematical operators are perhaps the most straightforward to those unfamiliar with Python. Let’s take this comparison operator as an example:
We also have membership operators (in and not in), which test whether an item is in an object. Here, we test whether an integer is included in a list of integers:
Python also offers identity operators, denoted by the is and is not keywords. These operators differ from the = operator, which compares two objects to see if they’re equal. Identity operators do not evaluate equality but, instead, check to see if the memory location of two objects is the same. Developers often use them to check if data assigned to a variable belongs to a certain class or type:
We can also use Python’s logical operators, and, or and not. The and condition in Python allows us to check if, given multiple expressions, all evaluate to “true.” A set of expressions using the or keyword will evaluate to “true” if one is in fact true:
These two operators use the same short-circuit evaluation that we saw in if-elif control structures. That is, if one condition in an expression using and evaluates to false and more conditions follow, Python will not evaluate them. It has what it needs to evaluate the entire expression to “false.” Likewise, if one condition in an expression with or evaluates to “true” and more conditions follow, Python will also not evaluate them. It has what it needs to evaluate the whole expression to “true.”
Now let’s look at an operator that’s a little more complex: the ternary operator.
If you have to code out a simple decision tree in your program, there’s a way to write it without following the prescribed structure of standard Python if-else statements. A ternary operator — sometimes called a conditional operator — follows a one-line format, and is an ideal choice for evaluating two non-complex expressions:
Here, the program first evaluates the <conditional_expression>, which is always in the middle and follows the if keyword. If it evaluates to “true,” the program runs the <first_expression>; but if it’s false, the program executes the <second_expression>. Instead of acting as a structure to control the order of program execution, the ternary operator carries out logical computations to define expressions, however achieving the same result as the former:
This has the same result as:
When should you use a conditional expression and when should you follow a regular if-else structure? As you might’ve guessed, you’ll go with an if-elif-else statement when working with more than two options, as ternary operators don’t support the elif clause.
But even if you do have two choices, we suggest going with a ternary only if your expressions are easily readable. After all, you should always strive to make your code readable, a goal that should trump even making your code as concise as possible.
For more on ternary operators, including on how to use them with dictionaries, tuples and lambdas, check out this StackOverflow answer.
Take One More Step to Your Future Career
In this article, we went over Python’s control structure before exploring the conditionality aspect of program execution. We looked at code snippets of the if-elif-then structure, touched on common operators in Python and discussed the ternary operator as an alternative to control structures.
Learning conditionality in Python is but one step you’ll take as a programming novice. In continuing your Python journey, check out Introduction to Programming Online Course to set yourself up for professional success.