Using conditions and match for rule-based programming in Python

By Abhinash Jena on January 25, 2025

Conditions in programming are logical expressions that evaluate to either true or false. They allow programs to make decisions by executing specific blocks of code based on whether a condition is met. Conditions determine the flow of a program by deciding which block of code should run under specific circumstances.

EXAMPLE

A login system checks if the username and password are correct before granting access to a guest.

Conditional expressions are integral to controlling flow structures like if elif and else which dictates the sequence of code execution.

OperatorMeaningExampleResult
== Equal to 5 == 5 TRUE
!= Not equal to 5 != 3 TRUE
> Greater than 7 > 5 TRUE
< Less than 3 < 5 TRUE
>= Greater than or equal to 5 >= 5 TRUE
<= Less than or equal to 3 <= 5 TRUE
Key operators of conditional expressions

A control program structure uses conditions to execute the code block when the condition is true.

temperature = input("Enter the current temperature (in °C): ") 

temperature = float (temperature)

if temperature > 30:

  print("It's hot today!")

elif temperature > 20:

  print("It's warm today!")

else:

  print("It's cold today!")

In the above code, the input() function prompts the user to enter the temperature. The value is converted to a float used float() to handle decimal inputs (e.g., 25.5°C).

Conditions

  • If the temperature exceeds 30°C: The program prints “It’s hot today!”.
  • If the temperature is between 20°C and 30°C: It prints “It’s warm today!”.
  • Otherwise, it prints “It’s cold today!”.

Avoiding poor readability and logical errors in Nested conditions

Automating decision-making with conditional expressions eliminates manual intervention and ensures consistency in a program. Nested conditions are conditions inside other conditions. Although nested conditions are the backbone of decision-making in programming, over-nesting conditions can make the code hard to read and understand. Furthermore, incorrectly written conditional expressions and ignoring edge cases or unusual scenarios can lead to unexpected outputs.

age = 25 

income = 30000

if age > 18:

  if income > 25000:

    if income < 50000:

      print("You are eligible for the program.")

In the above code, multiple nested if statements make the logic hard to understand. Simply noting the algorithmic steps can help combine nested conditions with and or operators.

OperatorMeaningExampleResult
AND Returns True if both conditions are true (5 > 3) and (2 < 4) TRUE
OR Returns True if at least one condition is true (5 > 3) or (2 > 4) TRUE

Now the nested conditions from the above code can be combined logically to simplify the code.

Algorithm

  • Check if the age is above 18.
  • Then check if the income is between 25, 000 and 50, 000.
  • If both are true, print the eligibility message.

Rewriting the code by combining the conditions into a single if expression.

if age > 18 and 25000 < income < 50000: 

  print("You are eligible for the program.")

This code is now concise and improves readability by reducing unnecessary nesting. Many times, nested conditions can create unintended logical errors.

temperature = 35 

if temperature > 20:

  if temperature > 30:

    print("It's very hot.")

  else:

    print("It's warm.")

In the above code, the inner else executes when temperature > 20 but not when temperature > 30. This creates a logical error since "It's warm." might print for higher temperatures as well.

Algorithm

  • Check if the temperature is > 20.
  • Then check if the temperature is > 30.
  • If not, print “It’s warm.”.

Rewriting the conditional expression to eliminate ambiguity.

if temperature > 30: 

  print("It's very hot.")

elif temperature > 20:

  print("It's warm.")

Furthermore, not using else or elif conditions can lead to execution of multiple conditions simultaneously resulting in incorrect or duplicate outputs.

score = 75 

if score >= 90:

  print("Grade: A")

if score >= 75:

  print("Grade: B")

if score >= 50:

  print("Grade: C")

Algorithm

  • Check the highest-grade range first (>= 90).
  • If not, check the next range (>= 75).
  • Finally, handle scores in the lowest range (>= 50).

Using if-elif-else to ensure mutually exclusive conditions and no overlapping of conditions.

if score >= 90: 

  print("Grade: A")

elif score >= 75:

  print("Grade: B")

elif score >= 50:

  print("Grade: C")

else:

  print("Grade: F")
TIP

Make conditions easier to understand by assigning a variable to the expression.

is_adult = age > 18 

has_high_income = income > 40000

if is_adult and has_high_income:

  print("Eligible")

Nested conditions are powerful for decision-making but can lead to pitfalls if not handled carefully. Moreover, thoughtful use of algorithms ensures the logic is robust and easy to follow.

Combining arithmetic, relational, and logical operations in one expression

Mixing and combining operators in a single conditional expression makes the code compact, efficient, and logical for complex decision-making and calculations. Combining multiple operations in a single expression also reduces the need for additional variables.

result = 5 + 3 > 6 and 2 * 3 

print(result)
#OUTPUT 

6

Algorithm

  • Step 1: Evaluate 2 * 3 → 6.
  • Step 2: Evaluate 5 + 3 → 8.
  • Step 3: Evaluate 8 > 6 → True.
  • Step 4: Combine with and: True and 6.
NOTE

In Python, any non-zero number is treated as True.

TIP

Use parentheses while writing expressions with mixed operators. This will make complex logic easier to follow.

if (price * quantity > 100) and (discount > 10): 

  print("Special discount applies")

For tasks involving comparisons, decision-making, and calculations, mixing operators is indispensable. Sophisticated mix operators that combine several types of operators can be confusing in the beginning. Therefore, it is important to understand the order of operator evaluation, called operator precedence. Python doesn’t evaluate operators from left to right. Instead, it follows rules of precedence and associativity. The following is the order of precedence with parentheses having the highest precedence order and is evaluated first.

  • Parentheses: ()
  • Arithmetic Operators: +, -, *, /, %
  • Relational Operators: >, <, ==, !=, >=, <=
  • Logical Operators: not, and, or
NOTE

Misunderstanding precedence will lead to incorrect results.

Let’s evaluate whether a user is eligible for a loan based on their age, income, and credit score. The rules are as follows:

  • The user must be at least 21 years old.
  • Their annual income must be greater than 40, 000.
  • Their credit score must be greater than 700.
age = 22 

income = 35000

credit_score = 750

# Loan eligibility logic

if age >= 21 and income > 40000 or credit_score > 700:

  print("Eligible for loan")

else:

  print("Not eligible for loan")
#OUTPUT 

Eligible for loan

The problem with the above code is the misunderstanding of the operator precedence where and has higher precedence than or. Thus, the condition is evaluated as:

  • age >= 21 AND income > 40000 OR
  • credit_score > 700

Therefore, the unintended outcome is if either credit_score > 700 or the and condition is true, the result is true. To match the intent of the algorithm, group conditions explicitly with parentheses.

if age >= 21 and (income > 40000 and credit_score > 700): 

  print("Eligible for loan")

else:

  print("Not eligible for loan")
#OUTPUT 

Not eligible for loan

Here, the and condition (income > 40000 and credit_score > 700) is evaluated first. Both income and credit_score conditions must be true for the second and to pass.

What makes the match statement more powerful?

The match statement is a new feature in Python that enables pattern matching. It is often compared to if-elif-else chains because it evaluates conditions and executes specific blocks of code. However, match is more powerful as it allows matching patterns rather than just conditions.

color = "red"

match color:

  case "red":

    print("Stop!")

  case "yellow":

    print("Slow down!")

  case _:

    print("Go!")
NOTE

_ is the default case like else in the if expression.

match can easily handle complex patterns, which would be cumbersome with if-elif.

data = {"type": "error", "code": 404} 

match data:

  case {"type": "error", "code": 404}:

    print("Page not found!")

  case {"type": "error", "code": 500}:

    print("Server error!")

  case {"type": "success"}:

    print("Operation successful!")

  case _:

    print("Unknown response.")
TIP

Use the | operator to combine cases with similar logic.

match day: 

  case "Saturday" | "Sunday":

    print("Weekend")

  case _:

    print("Weekday")

match also allows matching against specific patterns like tuple structure. It is easier to handle structured data with match compared to multiple if checks.

shape = (3, 4, 5) 

match shape:

  case (3, 4, 5): # Match specific tuple

    print("This is a triangle.")

  case (4, 4):

    print("This is a square.")

  case (x, y, z):

    print(f"This is a custom shape with dimensions: {x}, {y}, {z}.")

  case _:

    print("Unknown shape.")

The match statement is a cleaner and more powerful alternative to if-elif-else when dealing with:

  • Multiple static comparisons.
  • Pattern matching for complex data structures.
  • Readability in structured cases.

However, for dynamic conditions or logical comparisons, if-elif-else is more suitable. Choosing between them depends on the specific use case and the nature of the conditions.

NOTES

I am an interdisciplinary educator, researcher, and technologist with over a decade of experience in applied coding, educational design, and research mentorship in fields spanning management, marketing, behavioral science, machine learning, and natural language processing. I specialize in simplifying complex topics such as sentiment analysis, adaptive assessments and data visualizatiion. My training approach emphasizes real-world application, clear interpretation of results and the integration of data mining, processing, and modeling techniques to drive informed strategies across academic and industry domains.

Discuss

1 thought on “Using conditions and match for rule-based programming in Python”