Simple Arithmetic Operations Using Python’s Match-Case Statements (Python 3.10+)
In Python 3.10 and above, the match-case construct was introduced as a more powerful and flexible way to handle control flow. If you’re using Python 3.10 or later, this is an excellent opportunity to explore the new match-case statement to implement arithmetic operations. In this blog, I will show you how to use the match-case statement to perform basic arithmetic operations such as addition, subtraction, multiplication, and division.
Understanding Python’s match-case Statement
The match-case statement in Python is part of a more general approach to pattern matching. It enables cleaner, more readable control flow based on conditions, which is especially useful when handling multiple cases, like performing arithmetic operations.
If you’re following along with this tutorial, make sure you have Python version 3.10 or higher installed on your machine.
Learn more about Python Arithmetic Operators here.
Example: Performing Arithmetic Operations Using match-case
In this demonstration, I will show you how to implement arithmetic operations using Python’s match-case statement. This allows users to input two numbers and select an operation, which will be carried out based on their choice.
Here is the code for performing the four basic arithmetic operations:
"""
This 'match'-'case' statement feature is available from Python version 3.10 onwards.
"""
def arithmetic_operations(operation, first, second):
"""
This function performs arithmetic operations like addition, subtraction, multiplication, and division.
:param operation: Operation type - (1) addition, (2) subtraction, (3) multiplication, (4) division.
:param first: The first number
:param second: The second number
:return: None
"""
match operation:
case 1:
addition = first + second
print(f"Addition of {first} + {second} = {addition}")
case 2:
subtraction = first - second
print(f"Subtraction of {first} - {second} = {subtraction}")
case 3:
multiplication = first * second
print(f"Multiplication of {first} * {second} = {multiplication}")
case 4:
if second == 0:
print("The divisor must not be zero. Please restart the process.")
return False
division = first / second
print(f"Division of {first} / {second} = {division}")
case _:
print("Re-select a valid operation")
if __name__ == "__main__":
while True:
x = float(input("Enter your first number: "))
y = float(input("Enter your second number: "))
print("1. Addition | 2. Subtraction | 3. Multiplication | 4. Division")
op = int(input("Enter a number for the operation: "))
arithmetic_operations(op, x, y)
con = input("Do you want to continue (y/n): ")
if con.lower() == 'n':
break
Explanation of the Code
- Function Definition:
The functionarithmetic_operationsis defined to take three arguments:operation(which specifies the type of arithmetic operation),first(the first number), andsecond(the second number). - The
match-caseStatement:
Thematch-casestatement is used here to check the value ofoperationand execute the corresponding block of code based on the user’s input. The four cases represent addition, subtraction, multiplication, and division. - Case Default:
Thecase _syntax is used to handle invalid inputs, printing a message that prompts the user to select a valid operation. - Error Handling for Division:
Inside thecase 4(for division), there’s an additional check to prevent division by zero. Ifsecond == 0, a message is displayed, and the function returnsFalse. - Loop for Continuous Input:
The program runs in awhile Trueloop, continuously prompting the user for input until they choose to exit by entering ‘n’ when asked if they want to continue.
How This Works
- User Input:
- The user is prompted to enter two numbers.
- Then, they are asked to select an arithmetic operation (1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division).
- Performing Operations:
- Based on the user’s choice, the appropriate arithmetic operation is performed using the
match-casestatement. - The result of the operation is then displayed.
- Based on the user’s choice, the appropriate arithmetic operation is performed using the
- Re-running or Exiting:
- After displaying the result, the program asks if the user wants to continue. If they enter ‘n’, the loop exits, and the program terminates.
Why Use match-case for Arithmetic Operations?
While using if-elif-else statements for simple conditions is common in earlier Python versions, the match-case statement introduced in Python 3.10 makes the code cleaner and more readable, especially when dealing with multiple cases. It’s easier to scale and maintain, particularly when adding new types of operations or conditions.
Conclusion
By leveraging Python 3.10’s match-case statements, we can implement cleaner and more efficient arithmetic operations. This feature helps reduce the need for multiple if-elif branches, making the code more readable and maintainable.
Remember, the match-case statement is available starting from Python 3.10, so ensure you’re using a version that’s 3.10 or newer.
Read More
Read more about Python’s match case here – Click Here
| Related Post |
|---|
| Simple Arithmetic Operations using PHP |