Python Decision Making
Python Decision Making
Section titled “Python Decision Making”Decision making involves anticipating conditions that might occur during program execution and specifying actions based on whether those conditions are met.
Decision structures evaluate expressions, which result in a Boolean value: True or False. Based on this outcome, your program decides which block of code to execute.
The general flow of decision making often looks like this: Check a condition. If it’s true, perform Action A. If it’s false, perhaps check another condition or perform Action B.
Understanding Truthiness in Python
Section titled “Understanding Truthiness in Python”In Python, values are evaluated in a Boolean context (like in an if statement). The following are considered False:
- The boolean value
Falseitself. - The special object
None. - Numeric types equal to zero (e.g.,
0,0.0,0j). - Empty sequences (e.g.,
'',(),[]). - Empty mappings (e.g.,
{}). - Objects from user-defined classes that implement a
__bool__()or__len__()method returningFalseor0.
All other values are generally considered True. This concept is often called “truthiness”.
Python provides the following types of decision-making statements:
| Statement | Description |
|---|---|
if statements | Executes a block of code only if a specific condition is True. |
if...else statements | Executes one block of code if a condition is True and another block if it is False. |
if...elif...else statements | Checks multiple conditions in sequence and executes the block corresponding to the first True condition. An optional else block runs if none of the conditions are True. |
Nested if statements | You can place if, elif, or else statements inside the blocks of other decision-making statements. |
Let’s explore these structures.
Basic if Statement Example
Section titled “Basic if Statement Example”Here’s a simple example demonstrating an if statement:
#!/usr/bin/env python3
temperature = 35
# Use modern f-string formattingif temperature > 30: print(f"Temperature is {temperature}. It's hot outside!")
print("Execution finished.")When the above code is executed, it produces:
Temperature is 35. It's hot outside!Execution finished.if...elif...else Example
Section titled “if...elif...else Example”Using elif (else if) allows checking multiple conditions:
#!/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"Score: {score}, Grade: {grade}")Output:
Score: 75, Grade: CSingle Statement Suites (One-Liners)
Section titled “Single Statement Suites (One-Liners)”If the code block for an if, elif, or else clause consists only of a single statement, you can place it on the same line as the header. However, for readability (following PEP 8 guidelines), it’s generally recommended to use separate lines and indentation, especially for more complex logic.
Example of a one-line if clause:
#!/usr/bin/env python3
var = 100
# Note: idiomatic Python avoids parentheses around the conditionif var == 100: print("Value of expression is 100")
print("Goodbye!")When the above code is executed, it produces:
Value of expression is 100Goodbye!Further Resources
Section titled “Further Resources”For more details on control flow, check the official Python documentation: https://docs.python.org/3/tutorial/controlflow.html#if-statements