Python 3 - Decision Making
Python 3 - Decision Making
Section titled “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.
Truth Value Testing
Section titled “Truth Value Testing”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__()returnsFalseor__len__()returns0. - Considered True: All other values, including non-empty sequences/collections and non-zero numbers.
Decision Making Statements
Section titled “Decision Making Statements”Python provides the following statements for decision making:
| Statement | Description |
|---|---|
if statements | Executes a block of code only if a specified condition is True. |
if...else statements | Executes one block of code if the condition is True and another block if it is False. |
if...elif...else statements | Checks 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 statements | Allows 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 if Statement
Section titled “The if Statement”The simplest form. The code block following the if statement is executed only when the condition evaluates to True.
Syntax
Section titled “Syntax”if condition: # Code to execute if condition is True statement(s)Example
Section titled “Example”#!/usr/bin/env python3
temperature = 35
if temperature > 30: print("It's a hot day!")
print("Goodbye!") # This line executes regardless of the conditionOutput:
It's a hot day!Goodbye!The if...else Statement
Section titled “The if...else Statement”Provides an alternative path when the if condition is False.
Syntax
Section titled “Syntax”if condition: # Code to execute if condition is True statement(s)_if_trueelse: # Code to execute if condition is False statement(s)_if_falseExample
Section titled “Example”#!/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.The if...elif...else Statement
Section titled “The if...elif...else Statement”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.
Syntax
Section titled “Syntax”if condition1: # Code for condition1 True statement(s)_1elif condition2: # Code for condition1 False, condition2 True statement(s)_2elif condition3: # Code for condition1/2 False, condition3 True statement(s)_3# ... more elif blocks as neededelse: # Code if none of the above conditions are True statement(s)_elseExample: Grading System
Section titled “Example: Grading System”#!/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: CNested if Statements
Section titled “Nested if Statements”You can place conditional statements inside other conditional statements to handle more complex logic.
Example
Section titled “Example”#!/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-negativeNumber is PositiveNumber is OddWhile 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.
Single Statement Suites (Inline if)
Section titled “Single Statement Suites (Inline if)”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.
Example
Section titled “Example”#!/usr/bin/env python3
var = 100if var == 100: print(f"Value of expression is {var}") # Single statement on same line
print("Good bye!")Output:
Value of expression is 100Good bye!A more common and often preferred single-line conditional construct is the ‘ternary operator’ or conditional expression:
#!/usr/bin/env python3
age = 20status = "Adult" if age >= 18 else "Minor"print(f"The person is a {status}.")Output:
The person is a Adult.