“Unlocking Python’s Potential: A Beginner’s Guide to Conditional Statements”

Jeeshan
“Grokking Python Fundamentals”
8 min readJul 22, 2024

Introduction to Conditional Statements in Python

Conditional statements are a fundamental part of programming, allowing the code to make decisions and react differently based on different inputs or states. In Python, conditional statements evaluate whether a condition is true or false, and then execute specific blocks of code accordingly. These decisions help control the flow of execution in a program, making it dynamic and responsive.

The primary conditional statements in Python include if, elif, and else. Additionally, Python 3.10 introduced the match statement, akin to switch-case statements in other languages, which is used for pattern matching. Here’s what you’ll learn about conditional statements in this chapter:

  • Python — If…Else: Basics of making decisions in Python using if, elif, and else statements.
  • Python — Match Case: Understanding the new match statement for pattern matching, available from Python 3.10.

By mastering these constructs, you can write more complex and efficient Python scripts that perform different actions based on different inputs or other conditions.

Real-World Applications of Conditional Statements

Conditional statements are used extensively across various fields to make logical decisions based on specific conditions. Here are some practical real-world applications:

  1. User Input Validation: In software applications, conditional statements check whether the user input meets certain criteria, such as ensuring a user enters a valid email address or password during registration.
  2. Control Flow in Applications: They determine the flow of execution based on certain conditions, such as displaying different screens or information in a mobile app depending on the user’s choices or actions.
  3. Gaming: In video game development, conditional statements control game dynamics such as changing player abilities, adjusting difficulty levels, or triggering events based on player actions.
  4. Healthcare: Medical software systems use conditionals to alert staff about patient vitals that fall outside of safe thresholds, or to recommend treatment plans based on diagnostic inputs.

These examples illustrate the versatility and critical importance of conditional statements in programming, enabling tailored responses and intelligent behavior in software systems.

Python — If…Else

The if, elif, and else statements in Python are fundamental to controlling the flow of execution based on conditions. These statements allow you to execute specific blocks of code depending on whether certain conditions are true or false.

Below, we’ll break down how to use these constructs effectively across three sections, each focused on a different aspect of conditional execution.

if condition:
# block of code to execute if the condition is true
  • condition: This can be any expression that evaluates to True or False. If the condition is True, the code inside the block will execute.

Example

# Assigning a value to x
x = 10

# Checking if x is greater than 5
if x > 5:
# This block of code executes only if the above condition is true
print("x is greater than 5") # Output: x is greater than 5

Explanation:

  • x = 10: Set the variable x to 10.
  • if x > 5: Check if x is greater than 5.
  • print(...): Since x is indeed greater than 5, the message "x is greater than 5" is printed to the console.

The else Statement

The else Statement

The else statement complements the if statement and specifies a block of code to be executed if the if condition is false.

Example

if condition:
# block of code to execute if the condition is true
else:
# block of code to execute if the condition is false
  • The else block only executes when the if statement’s condition evaluates to False.

Example

# Assigning a value to x
x = 3

# Checking if x is greater than 5
if x > 5:
# This block of code executes only if the above condition is true
print("x is greater than 5")
else:
# This block of code executes if the 'if' condition is false
print("x is not greater than 5") # Output: x is not greater than 5

Explanation:

  • x = 3: Set the variable x to 3.
  • if x > 5: Check if x is greater than 5.
  • else: Since x is not greater than 5, the else block executes.
  • print(...): Prints "x is not greater than 5".

The elif Statement

The elif (else if) statement allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.

Syntax

if condition1:
# block of code to execute if condition1 is true
elif condition2:
# block of code to execute if condition2 is true
else:
# block of code to execute if all conditions are false

6

# block of code to execute if all conditions are false

. . .

  • elif allows for multiple conditions to be checked, each one after the previous one has evaluated to False.

Example

# Assigning a value to x
x = 15

# Checking if x is greater than 20
if x > 20:
# This block of code executes only if the above condition is true
print("x is greater than 20")
# Checking another condition if the first 'if' condition is false
elif x > 10:
# This block of code executes if the 'elif' condition is true
print("x is greater than 10 but not more than 20") # Output: x is greater than 10 but not more than 20
else:
# This block of code executes if all the above conditions are false
print("x is 10 or less")

Explanation:

  • x = 15: Set the variable x to 15.
  • if x > 20: Check if x is greater than 20.
  • elif x > 10: Since x is not greater than 20 but is greater than 10, execute this block.
  • print(...): Prints "x is greater than 10 but not more than 20".

This lesson provides a clear, step-by-step guide to using if, elif, and else statements in Python, covering their purposes, syntaxes, and practical examples with detailed explanations.

Python — Match Case

The match case statement, introduced in Python 3.10 as a structural pattern matching tool, is designed to simplify and enhance readability when dealing with complex conditional logic. It offers a more readable and concise alternative to multiple if...elif...else statements, especially when testing a variable against multiple conditions.

The match statement is similar to the switch case statements found in other languages but is more powerful due to its capabilities for pattern matching.

Syntax of the Match Statement

The match statement allows you to compare a value against several possible matches. Each case can execute a block of code designed for that specific match.

match expression:
case pattern1:
# block of code for pattern1
case pattern2:
# block of code for pattern2
case _:
# block of code for unmatched cases (default case)
  • expression: This is the value that you're comparing against the patterns in each case.
  • pattern: These are specific conditions or values that the expression might match. Python checks the patterns in the order they are written.
  • _: This is a wildcard pattern that acts as the default case, catching all values that don't match any previous pattern.

Execution Flow

Example

# Assign the status code value to the variable
status_code = 404

# Begin the match statement to evaluate the status_code
match status_code:
# First case: check if status_code is 200
case 200:
# Execute this print statement if the above case matches
print("Success") # This would print "Success" if status_code were 200

# Second case: check if status_code is 404
case 404:
# Execute this print statement if the above case matches
print("Not Found") # This prints "Not Found" since status_code is 404

# Third case: check if status_code is 500
case 500:
# Execute this print statement if the above case matches
print("Server Error") # This would print "Server Error" if status_code were 500

# Default case: executed if none of the above cases match
case _:
# Execute this print statement if no cases match
print("Unknown status code") # This would print if no other case matched

Explanation:

  • status_code = 404: Assigns the value 404 to the variable status_code.
  • match status_code: Starts a match statement that will check the value of status_code.
  • case 200: Checks if status_code equals 200. It does not, so it skips to the next case.
  • case 404: Checks if status_code equals 404. It does, so it executes the print statement.
  • The remaining cases and the default case (case _) are not executed because a match has already been found.

Combined Cases in Match Statement

In the match statement, you can handle multiple possible values for a single case using the | operator, which functions like an "or" in this context. This is useful when different values should trigger the same response, making your code cleaner and more straightforward.

Example

# Define a variable for the day of the week
day = "Tuesday"

# Use match to handle actions based on the day
match day:
case "Monday" | "Friday":
print("Start of the work week")
case "Wednesday" | "Tuesday":
print("Midweek")
case _:
print("Another day of the week")

Explanation:

  • day = "Tuesday": Assigns the string "Tuesday" to the variable day.
  • match day:: Begins a match statement that evaluates the variable day.
  • case "Monday" | "Friday":: Checks if day is either "Monday" or "Friday". If so, executes the associated block.
  • case "Wednesday" | "Tuesday":: Checks if day is either "Wednesday" or "Tuesday". If so, executes the associated block.
  • case _: : The wildcard case _ catches all other values that haven't matched any previous cases.

List as the Argument in Match Case Statement

The match statement can also work with lists as arguments, allowing you to match against the contents of a list. This is particularly useful for scenarios where you want to check the structure or presence of certain elements in a list.

Example

# Define a list of colors
colors = ["red", "blue", "green"]

# Matching against the first element in the list
match colors:
case ["red", *others]:
print("Red is the first color")
case ["blue", *others]:
print("Blue is the first color")
case _:
print("Different first color")

Explanation:

  • colors = ["red", "blue", "green"]: Assigns a list of three colors to the variable colors.
  • match colors:: Starts the match statement that checks the colors list.
  • case ["red", *others]:: Matches if the first element in the list is "red". The *others is a wildcard that captures the rest of the list, regardless of its contents.
  • case ["blue", *others]:: Matches if the first element is "blue", with *others again capturing the rest of the list.
  • case _: : Catches any list that doesn't start with "red" or "blue".

Using “if” in “Case” Clause

You can incorporate conditions within a case clause using the if keyword to add more specific logic to your matches. This allows for detailed and conditional pattern matching within the match statement.

Example

# Define a tuple for a person's age and occupation
person = (25, "Engineer")

# Use match to handle different conditions
match person:
case (age, profession) if age > 20 and profession == "Engineer":
print(f"Adult Engineer aged {age}")
case _:
print("Different profession or age group")

Explanation:

  • person = (25, "Engineer"): Assigns a tuple containing an integer and a string to person.
  • match person:: Initiates a match statement to evaluate person.
  • case (age, profession) if age > 20 and profession == "Engineer":: Matches if person is a tuple where the first element (age) is greater than 20 and the second element (profession) is "Engineer".
  • case _: : Catches all other values and patterns not matched by the first case.

These explanations and examples provide a thorough look into using the match case statement effectively, illustrating its power and flexibility in handling complex conditional logic in Python.

--

--

Jeeshan
“Grokking Python Fundamentals”

Data Analyst Enthusiast | Unveiling Insights Through Numbers | Helping You Navigate the World of Data Science | Exploring the Frontiers of ML and Generative AI