Decision making is a core concept of software development that allows a developer’s code to dynamically respond to a situation based on different conditions. In Python, decision making is achieved by using conditional statements and control structures, such as if and if-else statements. This programming tutorial discusses the concepts and techniques used for decision making in Python, and talks about advanced features such as nested conditionals and boolean expressions.
Jump to:
How to Use the if Statement in Python
In Python (and other programming languages), the most basic type of decision making is the if statement. It allows programmers to execute a given block of code only if a certain condition is true. For instance, if you were writing a program that was creating a peanut butter and jelly sandwich, you might have the program check if there was any peanut butter. If there was, the program would continue making the sandwich; if not, it would exit out of the program.
Here is the syntax for a Python if statement:
if condition:
# Code to execute if condition is True
Here is a code example demonstrating how to use an if statement in Python:
peanutButter = 1 if peanutButter > 0: print("You have peanut butter. Let’s make our sandwich!")
In the above code example, we create a variable named peanutButter and assign it a value of 1, indicating that we have peanut butter. Next, we use an if statement to check if the value of peanutButter is greater than 0. Since it is, Python moves on to the indented code beneath the if statement and executes that code – in our case, a print() statement that prints the text: “You have peanut butter. Let’s make our sandwich!”.
Had the value of peanutButter been less than 1, the program would have skipped the indented code and moved onto the next block of code. In this case, there are no other blocks of code, so Python would have simply exited the program without doing anything else.
Read: 4 Python Courses to Enhance Your Career
if-else Statement in Python
While if statements on their own are a powerful structure, they are are limited if we want users to have multiple options in our programs. For instance, in our peanut butter and jelly application, the program simply gives up if there is no peanut butter. Ideally, there would be an alternative option rather than just giving up and leaving us hungry.
To give the user (or the program) more options, we could introduce the if-else statement, which expands upon the basic if statement by allowing for an alternative block of code to execute if a condition is false.
Here is the syntax for the if-else statement in Python:
if condition: # Code to execute if condition is True else: # Code to execute if condition is False
Here is an example of how to use an if-else statement in Python:
peanutButter = 1 if peanutButter > 0: print("You have peanut butter. Let’s make our sandwich!") else: print("You have no peanut butter. No sandwich for you!")
The above code works in the same manner as our original example, only now if the value of peanutButter is not greater than 0, the program will skip to the else clause and execute the indented code beneath it before exiting the program.
Read: Top Bug Tracking Tool for Python
elif Statement in Python
In our above example, we gave the program two possible outcomes – one for if the value of peanutButter was greater than 0, and another if it was less than 0, symbolizing if you had peanut butter or not to make your sandwich.
But what happens if you have more than two conditions that you want to check for? In that instance, you will want to make use of the if-elif-else statement. The elif (or “else if”) lets programmers check additional conditions. The syntax for elif in Python is:
if condition1: # Code to execute if condition1 is True elif condition2: # Code to execute if condition2 is True else: # Code to execute if no conditions are True
Here is an example of how to use lif in your Python programs:
peanutButter = 1 if peanutButter > 0: print("You have peanut butter. Let’s make our sandwich!") elif peanutButter < 0: print("You have no peanut butter. No sandwich for you!") else: print("Maybe you should go check to see how much peanut butter you have…")
In this example, we have three conditions to check for. First, if the value of peanutButter is greater than 0. Second, if the value of peanutButter is less than 0. Third, a check to see if neither of these conditions is true. Only if the first two checks are false will the final else statement execute.
Nested Conditionals in Python
There are times when you will need to test for more complex decision making scenarios. In these instances, you will want to use something known as nesting or nesting conditionals. We will move away from our peanut butter sandwich example to better showcase how this works. In general, if you want to check for more complex conditions, ensure your indentation is correct for each if check. Consider the following:
iq = 10 if iq > 5: if iq > 7: print("IQ is greater than 7") else: print("IQ is between 5 and 7") else: print("IQ is not greater than 5")
Above, we assign a value to the variable iq and then perform several nested if statements. The first if check looks to see if iq is greater than 5. If it is not, then the program skips the indented blocks of code and executes the final else statement. If, however, the value of iq is greater than 5, then the program moves on to the next indented if statement, which checks to see if the value is greater than 7. If this evaluates to true, then it executes the first print statement. If it is false, it executes the indented else and prints: “IQ is between f and 7”.
Since the value of iq is 10, the output of this program would be:
IQ is greater than 7
Boolean Expressions in Python
In Python, a boolean expression is a condition that evaluates to true or false. Boolean expressions are used alongside conditional statements to decide which code block should execute for a given set of criteria. Used in conjunction with comparison operators, such as == (equal to), != (not equal to), and greater than/less than operators, boolean expressions become a great way to perform decision making in an application.
Here is an example of how to use boolean expressions in Python:
x = 50 y = 100 if x < y: print("x is less than y")
Use Cases for Decision Making
Decision making plays a role in nearly every program type imaginable. For example, you can use decision making in the following scenarios:
- Authenticating users: Check to see if the username and password match
- Control temperatures: Check to see if a system is at the right temperature and then adjust accordingly if not
- Video game logic: Check to see if a character hits another character or misses, then check to see how much damage is done based on the other character’s armor rating
- User options: Check to see if a user wants to update an application now, or later. This is a good example of a boolean check using “Yes” or “No” as true and false.
Final Thoughts on Python Decision Making
In this tutorial we discussed the concept of decision making in Python. We learned how to evaluate expressions and have our code execute different blocks of code based on criteria. In particular, we learned how to create if, else, and elif statements, as well as how to nest conditional statements and use boolean expressions to evaluate scenarios that require a true or false outcome.
Read: Top Python Frameworks