By the end of this lesson, you will be able to control program flow using Python's conditional statements: if, elif, else, nested structures, and ternary expressions.
What it is
Conditional logic allows a program to make decisions. Instead of executing every line sequentially, Python evaluates a boolean expression (True or False). If the condition is True, the indented block of code runs; otherwise, it skips to the next condition or block. The core keywords areif for the initial check, elif (short for "else if") for subsequent checks, and else for the default case when no conditions are met. Related terms include "boolean expressions," "indentation blocks," and "control flow."
Why it matters
- Dynamic Behavior: Programs can react differently based on user input, data values, or system states.
- Error Handling: You can prevent crashes by checking if a value exists or is valid before processing it.
- Efficiency: Skipping unnecessary code execution saves time and resources in complex applications.
- Readability: Proper use of
elifchains makes logic easier to follow than multiple independentifstatements.
Syntax or steps
Python relies on indentation (whitespace) rather than braces to define code blocks. The basic structure is: 1. Start withif condition:.
2. Indent the code that runs if true.
3. Optionally add elif another_condition: followed by indented code.
4. Optionally add else: followed by indented code for all other cases.
For simple assignments, use the ternary operator: value = true_value if condition else false_value.
Example
def check_access(age, has_ticket):
# Standard if-elif-else chain
if age < 18:
status = "Minor"
elif not has_ticket:
status = "No Ticket"
else:
status = "Granted"
# Ternary expression for concise assignment
message = f"Access {status}" if status == "Granted" else "Access Denied"
return message
# Test cases
print(check_access(25, True)) # Output: Access Granted
print(check_access(17, True)) # Output: Access Denied
print(check_access(20, False)) # Output: Access Denied
Explanation:
The function first checks if the user is under 18. If not, it checks if they lack a ticket. If both fail, access is granted. The variable message uses a ternary expression to assign a string based on whether status equals "Granted". This demonstrates how to combine multi-line logic with single-line conditional assignments.
Common mistakes
- Missing Colons: Forgetting the colon (
:) at the end ofif,elif, orelselines causes aSyntaxError. - Inconsistent Indentation: Mixing tabs and spaces or failing to indent the block under the condition leads to
IndentationError. - Using Assignment (=) instead of Comparison (==): Writing
if x = 5:is invalid syntax in Python (unless using walrus operators in specific contexts), whereasif x == 5:is correct. - Unreachable Code: Placing a broad condition like
if True:orelse:before more specificelifblocks prevents the specific logic from ever running.
When to use it
Use standardif/elif/else blocks when you need to execute multiple lines of code or perform side effects (like printing or modifying lists). Use ternary expressions only for simple value assignments where readability remains high.
| Feature | If/Elif/Else Block | Ternary Expression |
|---|---|---|
| Complexity | High (multi-line) | Low (single line) |
| Side Effects | Supported | Not recommended |
| Readability | Clear for complex logic | Clear for simple choices |
Practice
Guided Exercise: Write a script that takes a number as input. Print "Positive" if greater than 0, "Negative" if less than 0, and "Zero" if equal to 0. Use anif-elif-else structure.
Challenge: Refactor your solution to use a ternary expression to assign the result to a variable named label, then print label. Hint: You may need nested ternaries or stick to the block structure for three-way branching clarity.
Quick check
Question: What happens if you omit theelse block in an if-elif chain and none of the conditions evaluate to True?
Answer: The program simply continues execution after the entire conditional block without running any of the internal code. No error occurs unless variables defined inside the block are accessed later.
Summary
Conditional logic is fundamental to programming, allowing Python to branch execution based on dynamic data. Mastering the distinction between multi-lineif/elif/else blocks for complex actions and ternary expressions for simple assignments ensures your code is both functional and readable. Always pay attention to indentation and colons to avoid common syntax errors.