07. Python Control Flow - Conditional Statements
π Master the art of decision-making in Python! Learn to wield conditional statements like a pro β from simple `if` to advanced `match-case` for crafting elegant and responsive code. π‘
What we will learn in this post?
- π Introduction to Control Flow
- π if Statement
- π if-else Statement
- π if-elif-else Statement
- π Nested if Statements
- π Ternary Operator (Conditional Expression)
- π match-case Statement (Python 3.10+)
- π Conclusion!
Controlling the Flow π¦ in Your Code
Imagine your code as a recipe. Control flow lets you decide which steps to take, skip, or repeat. Itβs about guiding the computer on what to do and when to do it. Without it, programs would only execute one line after another, making them boring and inflexible. Control flow is essential for creating dynamic and responsive programs!
Pythonβs Secret: Indentation π
Unlike some languages that use curly braces {}, Python uses indentation to group lines of code into blocks. Think of it like outlining a document β the level of indentation shows which statements belong together. For example:
1
2
3
4
if x > 5:
print("x is big!") # Part of the 'if' block
y = x * 2 # Also part of the 'if' block
print("Done!") # Not part of the 'if' block
Correct indentation is crucial; incorrect indentation will cause errors! Make sure to use consistent spacing (usually four spaces) for each level of indentation.
- Why is this important? It makes Python code very readable and avoids the clutter of curly braces.
- Keep in mind: Consistency is key! Use spaces or tabs only. Donβt mix them!
graph LR
A[Start] --> B{Condition?};
B -- Yes --> C([<b style='color:#27ae60'>Execute Block</b>]);
C --> D([<b style='color:#8e44ad'>Next Statement</b>]);
B -- No --> D;
D --> E([<b style='color:#e74c3c'>End</b>]);
Types of Control Flow π
Conditional Statements: Decide which code to run based on conditions (using
if,elif, andelse).Loops: Repeat code blocks (using
forandwhileloops).
By mastering control flow, you unlock the true potential of programming!
Conditional Logic with βifβ Statements π
Letβs explore how if statements let your code make decisions!
Understanding the βifβ Syntax
The if statement checks if a condition is true. If it is, the code inside the if block runs. If not, that code is skipped.
1
2
if condition:
# Code to execute if the condition is true
The condition is a boolean expression, meaning it results in either True or False. Here are some examples:
Examples with Different Conditions π
- Example 1: Simple Comparison
1
2
3
x = 10
if x > 5:
print("x is greater than 5") #Output: x is greater than 5
- Example 2: Checking Equality
1
2
3
name = "Alice"
if name == "Alice":
print("Hello, Alice!") #Output: Hello, Alice!
- Example 3: Using
else
1
2
3
4
5
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult yet.") #Output: You are not an adult yet.
- Example 4: Using
elif(else if)
1
2
3
4
5
6
7
8
9
score = 75
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C") #Output: C
else:
print("D")
Hereβs a flowchart representing the if-else logic:
flowchart TD
A[Start] --> B{Condition?};
B -- Yes --> C([<b style='color:#27ae60'>True Block</b>]);
B -- No --> D([<b style='color:#e74c3c'>False Block</b>]);
C --> E([<b style='color:#8e44ad'>End</b>]);
D --> E;
Boolean expressions can use comparison operators like >, <, ==, !=, >=, <= and logical operators like and, or, not.
Conditional Control with If-Else Statements π
The if-else statement is your trusty tool in programming for making decisions. It lets your code follow one path if a condition is true, and another path if itβs false. Think of it like a fork in the road!
If-Else Syntax
The basic syntax looks like this:
1
2
3
4
if condition:
# Code to execute if the condition is TRUE
else:
# Code to execute if the condition is FALSE
- The
conditionis a boolean expression (something that evaluates toTrueorFalse). - The code inside the
ifblock executes only when the condition isTrue. - The code inside the
elseblock executes only when the condition isFalse.
Practical Examples
Here are some easy-to-understand examples:
- Even/Odd Checker
1
2
3
4
5
number = 7
if number % 2 == 0:
print("Even") # This will NOT print
else:
print("Odd") # Output: Odd
- Age Validation
1
2
3
4
5
age = 16
if age >= 18:
print("You are an adult.") # This will NOT print
else:
print("You are a minor.") # Output: You are a minor.
- Simple greeting based on Time of Day
1
2
3
4
5
time = 14 #2 PM
if time < 12:
print("Good Morning!") #This will NOT print
else:
print("Good Afternoon") #Output: Good Afternoon!
Conditional Logic with if-elif-else in Python π
Pythonβs if-elif-else statement is your go-to tool for handling multiple conditions in a program. Think of it like a branching path where your code takes different routes based on whether certain conditions are met.
How it Works π€
The if-elif-else chain evaluates conditions in a specific order.
- First, the
ifcondition is checked. If itβsTrue, the code block under it is executed, and the rest of the chain is skipped. - If the
ifcondition isFalse, Python moves to the firstelif(short for βelse ifβ) condition. It checks this condition, and if itβsTrue, its code block is executed, and the rest are skipped. - You can have multiple
elifconditions to check for various scenarios. - Finally, if none of the
iforelifconditions areTrue, theelseblock is executed. Theelseblock is optional and acts as a default action.
Python stops evaluating conditions as soon as it finds one that is True. This behavior is called short-circuiting.
Examples π
Grade Calculation
1
2
3
4
5
6
7
8
9
10
grade = 85
if grade >= 90:
print("A") #Output: A
elif grade >= 80:
print("B") #Output: B
elif grade >= 70:
print("C")
else:
print("Below C")
Menu Selection
1
2
3
4
5
6
7
8
9
10
choice = "2" #User has selected option 2
if choice == "1":
print("You selected Option 1")
elif choice == "2":
print("You selected Option 2") #Output: You selected Option 2
elif choice == "3":
print("You selected Option 3")
else:
print("Invalid choice")
In the grade example, since grade is 85, the second elif condition (grade >= 80) is True, so βBβ is printed. In the menu example, the second elif condition is True, so βYou selected Option 2β is printed.
Hereβs a simple flowchart illustrating the logic:
graph TD
A[Start] --> B{Condition 1?};
B -- True --> C([<b style='color:#27ae60'>Execute Block 1</b>]);
B -- False --> D{{<b style='color:#2980b9'>Condition 2?</b>}};
D -- True --> E([<b style='color:#27ae60'>Execute Block 2</b>]);
D -- False --> F{{<b style='color:#2980b9'>Condition 3?</b>}};
F -- True --> G([<b style='color:#27ae60'>Execute Block 3</b>]);
F -- False --> H([<b style='color:#e74c3c'>Execute Else Block</b>]);
C --> I([<b style='color:#8e44ad'>End</b>]);
E --> I;
G --> I;
H --> I;
Nested If Statements: A Guide π§
Nested if statements are if statements inside other if statements. Think of it like Russian nesting dolls! You use them when you need to check multiple conditions, where one condition depends on another.
When to Use Them? π€
Use them when the second condition only needs to be checked if the first one is true. For example:
1
2
3
4
5
6
7
8
9
10
age = 20
has_license = True
if age >= 18:
if has_license:
print("You can drive!") # Output: You can drive!
else:
print("You're old enough, but need a license.")
else:
print("You're too young to drive.")
Readability is Key! π
Deeply nested if statements can get messy. Indentation matters in Python and makes code look very ugly! To keep things readable:
- Keep nesting shallow (aim for no more than 2-3 levels).
- Use meaningful variable names.
- Add comments to explain complex logic.
Alternatives to Deep Nesting π‘
Consider these options:
elif(else if): Makes multiple conditions clearer.- Logical operators (
and,or): Combine conditions. For instance, in the previous example,if age >= 18 and has_license:would avoid the nestedif. - Functions: Break down complex logic into smaller, reusable parts.
Guard Clauses: Check for error condition and return immediately
1 2 3 4 5 6
def process_data(data): if data is None: return "Error: Data is None" #Proceed with processing if data isn't None #....
This method checks for the problematic cases early and exits, thus helping to avoid deep nesting for primary logic flow.
By applying these tips, your code will be much easier to understand and maintain.
Pythonβs Ternary Operator: A Concise If-Else π
Python offers a cool shorthand for simple if-else statements called the ternary operator. Think of it as a one-line if-else. Itβs structured like this: value_if_true if condition else value_if_false.
How it Works β¨
It evaluates the condition. If the condition is True, it returns value_if_true; otherwise, it returns value_if_false. Letβs see some examples:
1
2
3
4
5
6
7
8
9
10
11
12
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Adult
is_even = True
message = "Even" if is_even else "Odd"
print(message) # Output: Even
x = 5
y = 10
result = x if x < y else y
print(result) # Output: 5
When to Use It π€
The ternary operator is best used for:
- Assigning a value based on a simple condition.
- Keeping code concise and readable, especially when dealing with short, straightforward
if-elselogic. - Avoid it for complex conditions or nested
if-elsestatements, as it can become difficult to read.
Using it judiciously can make your Python code cleaner and more efficient.
Pythonβs Cool New Trick: The match-case Statement π€©
Python 3.10 brought us a handy tool called match-case, also known as structural pattern matching. Itβs like a super-powered if-elif-else that can check the structure of your data, not just values!
How it Works π οΈ
The basic syntax is:
1
2
3
4
5
6
7
8
match variable:
case pattern1:
# Do something if variable matches pattern1
case pattern2:
# Do something if variable matches pattern2
case _: # wildcard
# Default case if no other pattern matches
Hereβs a simple example:
1
2
3
4
5
6
7
8
9
command = "open file"
match command.split():
case ["open", file_name]:
print(f"Opening {file_name}...") # Output: Opening file...
case ["close"]:
print("Closing the application")
case _:
print("Invalid command")
Why Use match-case? π€
- Readability: Makes code cleaner and easier to understand, especially when dealing with complex data.
- Structure Matters: Unlike
if-elif-else, it can check the structure of lists, tuples, and even objects. - Conciseness: Often reduces the amount of code you need to write.
match-case vs. if-elif-else π₯
While if-elif-else checks conditions based on values, match-case checks based on the structure and optionally, values within that structure. match-case is particularly useful when you have different ways of structuring data and you need to handle each case differently.
Comparison Table: if-elif-else vs match-case
| Feature | if-elif-else | match-case (Python 3.10+) |
|---|---|---|
| Syntax | Simple, linear | Pattern matching, more expressive |
| Readability | Good for few conditions | Better for many/complex cases |
| Performance | Similar for small cases | Efficient for many patterns |
| Pattern Matching | Not supported | Supported (structural, value) |
| Default Case | else | case _ |
| Python Version | All versions | 3.10+ only |
| Use Case | Simple branching | Complex, pattern-based logic |
Summary: Use if-elif-else for simple, linear decisions. Use match-case for advanced pattern matching and when handling many distinct cases.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
point = (0,1)
match point:
case (0, 0):
print("Origin")
case (0, y): #capture pattern
print(f"On y-axis at y={y}") #output: On y-axis at y=1
case (x, 0):
print(f"On x-axis at x={x}")
case (x, y):
print(f"General point at ({x}, {y})")
match-case can greatly improve the clarity and conciseness of code in certain situations.
graph LR
A[Input Data] --> B{Match Statement};
B --> C{{<b style='color:#f39c12'>Case 1: Pattern Matches?</b>}};
C -- Yes --> D([<b style='color:#27ae60'>Execute Case 1 Code</b>]);
C -- No --> E{{<b style='color:#f39c12'>Case 2: Pattern Matches?</b>}};
E -- Yes --> F([<b style='color:#27ae60'>Execute Case 2 Code</b>]);
E -- No --> G{{<b style='color:#f39c12'>Case N: Pattern Matches?</b>}};
G -- Yes --> H([<b style='color:#27ae60'>Execute Case N Code</b>]);
G -- No --> I([<b style='color:#e74c3c'>Execute Default Case Code</b>]);
D --> J([<b style='color:#8e44ad'>End</b>]);
F --> J;
H --> J;
I --> J;
π― Practice Project Assignment
π‘ Project: Smart Restaurant Ordering System (Click to expand)
Your Challenge:
Build a comprehensive restaurant ordering system that uses all conditional statement types (if-elif-else, nested conditionals, ternary operators, and match-case).
Requirements:
Part 1: Menu Selection (if-elif-else)
- Display a menu with 5 categories: Appetizers, Main Course, Desserts, Beverages, Special
- Take user input for category selection
- Show items and prices for the selected category
- Calculate subtotal based on quantity ordered
Part 2: Discount Calculation (Nested Conditionals)
- Check if customer is a member (boolean)
- Check order amount thresholds:
- Members: 15% off for orders β₯ $50, 10% for orders β₯ $30
- Non-members: 10% off for orders β₯ $100, 5% for orders β₯ $50
- Apply appropriate discount
Part 3: Delivery Options (Ternary Operator)
- Use ternary operator to set delivery fee: $0 if order β₯ $50, $5 otherwise
- Use ternary to determine delivery time: "30-45 minutes" if distance < 5 km, "45-60 minutes" otherwise
Part 4: Payment Method (match-case)
- Accept payment method: "card", "cash", "wallet", "upi"
- Use match-case to apply: Card (2% fee), Cash (no fee), Wallet (1% cashback), UPI (0.5% cashback)
- Display final total with all fees/discounts
Bonus Challenges:
- Add input validation (check for valid menu items, quantities > 0)
- Create a tip calculator using ternary operator
- Use match-case for dietary preferences
- Add loyalty points calculator
Example Output:
Welcome to Smart Restaurant! π½οΈ Select category: 2 Main Course: Pizza x2 = $36.00 Member discount: 10% off ($3.60) Delivery: Free! (30-45 min) Payment (wallet): 1% cashback ($0.32) Final Total: $32.72 Thank you for ordering! π
Share Your Solution! π¬
Completed the project? Post your code in the comments below! Show us your creative approach! π¨
Conclusion
Thanks for sticking around until the end! π Did this post give you any new ideas?π‘ Or do you have any tips to share with the community? Leave a comment below and let us know! Weβre all ears!π Your insights are super valuable! β¨