Post

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. ๐Ÿ’ก

07. Python Control Flow - Conditional Statements

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, and else).

  • Loops: Repeat code blocks (using for and while loops).

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 condition is a boolean expression (something that evaluates to True or False).
  • The code inside the if block executes only when the condition is True.
  • The code inside the else block executes only when the condition is False.

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!

For more details on conditionals, you can also explore this tutorial.

Python If-Else

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 if condition is checked. If itโ€™s True, the code block under it is executed, and the rest of the chain is skipped.
  • If the if condition is False, Python moves to the first elif (short for โ€œelse ifโ€) condition. It checks this condition, and if itโ€™s True, its code block is executed, and the rest are skipped.
  • You can have multiple elif conditions to check for various scenarios.
  • Finally, if none of the if or elif conditions are True, the else block is executed. The else block 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")
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;
    D -- True --> E([<b style='color:#27ae60'>Execute Block 2</b>]);
    D -- False --> F;
    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 nested if.
  • Functions: Break down complex logic into smaller, reusable parts.
  • Guard Clauses: Check for error condition and return immediately

    ```python def process_data(data): if data is None: return โ€œError: Data is Noneโ€

    1
    2
    3
    
        #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.


More info on if statements

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-else logic.
  • Avoid it for complex conditions or nested if-else statements, 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

Featureif-elif-elsematch-case (Python 3.10+)
SyntaxSimple, linearPattern matching, more expressive
ReadabilityGood for few conditionsBetter for many/complex cases
PerformanceSimilar for small casesEfficient for many patterns
Pattern MatchingNot supportedSupported (structural, value)
Default Caseelsecase _
Python VersionAll versions3.10+ only
Use CaseSimple branchingComplex, 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.

More info on pattern matching

graph LR
    A[Input Data] --> B{Match Statement};
    B --> C;
    C -- Yes --> D([<b style='color:#27ae60'>Execute Case 1 Code</b>]);
    C -- No --> E;
    E -- Yes --> F([<b style='color:#27ae60'>Execute Case 2 Code</b>]);
    E -- No --> G;
    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;

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! โœจ

This post is licensed under CC BY 4.0 by the author.