Skip to content

Python 3 - Decision Making

Decision making is fundamental to programming. It allows your program to execute different blocks of code based on whether certain conditions are true or false. This enables programs to react dynamically to different inputs or situations.

Decision structures evaluate expressions that result in a Boolean value: True or False. Based on this outcome, the program chooses which path to follow.

Imagine a flowchart where you encounter a question (the condition). If the answer is ‘Yes’ (True), you follow one path; if the answer is ‘No’ (False), you follow another. Python provides specific statements to implement this logic.

In Python, conditions are evaluated in a boolean context. While the explicit boolean values are True and False, other values can also be treated as true or false in conditional statements:

  • Considered False: None, False (boolean), zero of any numeric type (0, 0.0, 0j), empty sequences ('', (), []), empty mappings ({}), empty sets (set()), objects where __bool__() returns False or __len__() returns 0.
  • Considered True: All other values, including non-empty sequences/collections and non-zero numbers.

Python provides the following statements for decision making:

StatementDescription
if statementsExecutes a block of code only if a specified condition is True.
if...else statementsExecutes one block of code if the condition is True and another block if it is False.
if...elif...else statementsChecks multiple conditions in sequence. Executes the block corresponding to the first True condition. An optional else block executes if none of the preceding conditions are True.
Nested if statementsAllows you to place if, elif, or else statements inside the code blocks of other if, elif, or else statements, creating more complex decision trees.

The simplest form. The code block following the if statement is executed only when the condition evaluates to True.

if condition:
# Code to execute if condition is True
statement(s)
#!/usr/bin/env python3
temperature = 35
if temperature > 30:
print("It's a hot day!")
print("Goodbye!") # This line executes regardless of the condition

Output:

It's a hot day!
Goodbye!

Provides an alternative path when the if condition is False.

if condition:
# Code to execute if condition is True
statement(s)_if_true
else:
# Code to execute if condition is False
statement(s)_if_false
#!/usr/bin/env python3
age = 17
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
print("Processing complete.")

Output:

You are not eligible to vote yet.
Processing complete.

elif stands for ‘else if’. It allows you to check multiple conditions sequentially. The first condition that evaluates to True will have its code block executed, and the rest of the elif/else blocks will be skipped. The final else block is optional and executes if none of the preceding if or elif conditions were True.

if condition1:
# Code for condition1 True
statement(s)_1
elif condition2:
# Code for condition1 False, condition2 True
statement(s)_2
elif condition3:
# Code for condition1/2 False, condition3 True
statement(s)_3
# ... more elif blocks as needed
else:
# Code if none of the above conditions are True
statement(s)_else
#!/usr/bin/env python3
score = 75
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
print(f"Your score is {score}, which corresponds to grade: {grade}")

Output:

Your score is 75, which corresponds to grade: C

You can place conditional statements inside other conditional statements to handle more complex logic.

#!/usr/bin/env python3
num = 15
if num >= 0:
print("Number is non-negative")
if num == 0:
print("Number is Zero")
else:
print("Number is Positive")
if num % 2 == 0:
print("Number is Even")
else:
print("Number is Odd")
else:
print("Number is Negative")

Output:

Number is non-negative
Number is Positive
Number is Odd

While nesting is possible, excessive nesting can make code hard to read. Consider refactoring complex nested conditions into separate functions or using other control flow structures if possible.

If the code block for an if (or elif, else) consists of only a single statement, you can place it on the same line as the header. However, this is often discouraged by style guides like PEP 8 for readability, especially for complex actions.

#!/usr/bin/env python3
var = 100
if var == 100: print(f"Value of expression is {var}") # Single statement on same line
print("Good bye!")

Output:

Value of expression is 100
Good bye!

A more common and often preferred single-line conditional construct is the ‘ternary operator’ or conditional expression:

#!/usr/bin/env python3
age = 20
status = "Adult" if age >= 18 else "Minor"
print(f"The person is a {status}.")

Output:

The person is a Adult.