Conditional operators match case and comparison in Python: from if to templates

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Conditional statements in Python: a complete guide

Conditional statements are a fundamental element of programming

They enable decision-making in code and the execution of specific actions only when given conditions are met. Python provides developers with a powerful set of tools for working with conditional logic.

Main types of conditional statements

The following types of conditional constructs are available in the Python programming language:

Classic if, elif and else constructs

Logical operators and, or, not

Comparison operators ==, !=, <, >, is, in

Structural pattern matching match case (starting from version 3.10)

Each of these tools has its particular use cases and is suitable for solving certain programming tasks.

Basic conditional constructs

Structure of if, elif, else

The basis of conditional logic in Python is the if-elif-else construct:

x = 10 if x > 0: print("Positive") elif x == 0: print("Zero") else: print("Negative")

Python uses indentation to define code blocks instead of braces. Proper use of indentation is critical because it is part of the language syntax.

Syntax specifics

Indentation in Python must be consistent throughout the code. It is recommended to use 4 spaces for each level of nesting. Mixing spaces and tabs may lead to runtime errors.

Comparison operators in Python

Python supports a wide range of comparison operators that allow creating complex conditions:

Arithmetic comparisons

== checks value equality != checks inequality < and > compare less than and greater than respectively <= and >= include equality in the comparison

Special operators

The is operator checks object identity in memory, not value equality. The in operator checks membership of an element in a collection.

s1 = "hello" s2 = "hello" print(s1 == s2) # True - value equality print(s1 is s2) # True for interned strings

String comparison and nuances

Python automatically interns short strings, which means identical strings may reference the same object in memory. This affects the result of comparisons using is.

Logical operators: and, or, not

Logical operators allow combining multiple conditions in one expression:

a = 5 b = 10 if a > 0 and b > 0: print("Both are positive")

Principles of logical operators

and returns True only when both conditions are true or returns True if at least one condition is true not negates the logical value

Short-circuit evaluation

Python uses short-circuit evaluation for logical expressions. That means if the result is already determined by the first operand, the second is not evaluated.

Nested conditional constructs

Conditional statements can be nested within each other to create more complex logic:

x = 15 if x > 0: if x < 10: print("Less than 10") else: print("10 or more")

Recommendations for use

Excessive nesting can hurt code readability. It is recommended to limit nesting to 3–4 levels and, if necessary, move complex logic into separate functions.

match case in Python 3.10+

Introduction to structural pattern matching

With the release of Python 3.10, the match case construct appeared, implementing structural pattern matching. It is a powerful alternative to traditional conditional statements for certain scenarios.

def http_status(code): match code: case 200: return "OK" case 404: return "Not Found" case 500: return "Server Error" case _: return "Unknown status"

Advantages of match case

Structural pattern matching provides cleaner and more readable code when working with multiple variants. There is no risk of forgetting a break as in switch statements of other languages.

Extended capabilities of match

Type-based matching

Match case allows checking data types directly in the pattern:

match value: case str(): print("This is a string") case int(): print("An integer")

Conditional checks inside case

Guard expressions allow adding additional conditions to patterns:

match x: case int() if x > 0: print("A positive number") case int() if x == 0: print("Zero") case _: print("Something else")

Destructuring and unpacking

Match case supports unpacking data structures, which is especially useful when working with tuples and dictionaries:

point = (3, 4) match point: case (0, 0): print("Origin") case (x, y): print(f"x={x}, y={y}")

Working with dictionaries in match case

Structural pattern matching works effectively with dictionaries, allowing you to check for keys and extract values:

data = {"type": "login", "user": "admin"} match data: case {"type": "login", "user": user}: print(f"User {user} logged in")

Choosing between if and match case

Selection criteria

The choice between if and match depends on the specific task:

For checking data types, match case is preferable When matching many exact values, match case is more readable For logical expressions and simple comparisons, if-elif-else is better

Practical recommendations

Match case gives better readability when dealing with five or more conditions. If-elif remains the universal solution for most tasks.

Practical usage examples

Handling user commands

command = input("Enter command: ") match command: case "start": print("Starting...") case "stop": print("Stopping") case _: print("Unknown command")

Handling API responses

response = {"status": "ok", "code": 200} match response: case {"status": "ok", "code": code} if code == 200: print("Success")

Comparison with counterparts in other languages

Differences from switch

Python match case has significant differences from switch in languages like C or JavaScript:

It does not require an explicit break to prevent fall-through It supports pattern and type matching It provides structural unpacking of data It prevents accidental fall-through between cases

Version compatibility

Match case is available only in Python 3.10 and later. To check compatibility, use:

import sys assert sys.version_info >= (3, 10)

Common mistakes and how to avoid them

Typical problems

Developers often face certain errors when working with conditional statements:

Using match case in Python versions earlier than 3.10 Omitting the default case (case _) Trying to use match for logical expressions Confusing value equality with type/identity checks

Solutions and prevention

To avoid mistakes, always specify the Python version in the project, include default cases, and clearly separate the use cases for if and match.

Performance optimization

Order of conditions

Place the most likely conditions at the start of an if-elif chain to improve performance. Python evaluates conditions sequentially.

Using dictionaries as an alternative

For simple value-to-action mapping, dictionaries can be faster than long if-elif chains:

status_messages = { 200: "OK", 404: "Not Found", 500: "Server Error" } message = status_messages.get(code, "Unknown status")

Best practices

Code readability

Use meaningful variable names in conditions. Avoid complex nested expressions; move them into separate variables.

Commenting

Complex conditions require comments that explain the business logic behind the checks.

Conclusion

Python provides two main approaches to building conditional logic. The classic if-elif-else constructs remain a universal and reliable tool for any situation. The modern match case construct opens new possibilities for structural pattern matching, working with patterns, and improving code readability.

The choice between these approaches should be based on the specifics of the task. In a well-designed application, both tools can be used together, each in the appropriate context.

Frequently asked questions

What is match case in Python?

Match case is a construct for structural pattern matching added in Python 3.10. It allows elegant handling of multiple value variants and patterns.

What is the main difference between match and if?

Match case is intended for pattern matching, supports unpacking data structures and type checks. If is better suited for logical expressions and complex conditional logic.

Is match available in Python 3.9?

No, match case is available only starting from Python 3.10 and later versions.

Can match and if be combined?

Yes, you can use additional if conditions inside case blocks. Such constructions are called guard expressions.

News