Arithmetic operations using switch case in python

42. Python Program to Perform Arithmetic Calculations using Switch Case.

How does this program work?

  • In this program we are going to learn about how to perform arithmetic calculations by using Switch Case in Python.
  • The integer entered by the user is stored in two variables a, b and also entered choice is stored in variable option.
  • By using switch case select one option then equivalent operation (Addtion, Subtraction, Multiplication, Division) can be performed by given logic.

Here is the code

//To Calculate Arithmetic Operations using Switch Case
def switch():
a = int(input("Enter first value: "))
b = int(input("Enter second value: "))
print("Press 1 for Addittion \nPress 2 for Subtraction \nPress 3 for Multiplication \nPress 4 for Division")
option = int(input("Enter your option: "))
if option == 1:
result = a+b
print("Addition : ", result)
elif option == 2:
result = a-b
print("Subtraction : ",result)
elif option == 3:
result = a*b
print("Multiplication : ", result)
elif option == 4:
result = a/b
print("Division : ",result)
else:
print("Invalid Value")
switch()

Arithmetic operations using switch case in python

Arithmetic operations using switch case in python

Introduction to Python Switch Case

Python Switch case is serious on conditional statements used in a case where we have too many if conditions. We have a switch function that accepts arguments and a series condition that fulfills the condition of the argument. If the condition does not match then, it goes to the next condition. We use the break to come out of the condition, and we also have a default condition. The default condition automatically executes if none of the conditions gets executed. The switch case also supports nesting, which means we can have another switch case inside a switch case condition.

Syntax:

This is the basic syntax of the switch case:

switch EXPR:
    case EXPR:
        SUITE
    case EXPR:
        SUITE
    ...
    else:
        SUITE

Examples of Python Switch Case

Below are the examples of a python switch case:

Example #1

As we know, python doesn’t have a switch case, so here we will use a switcher. It is similar to the switch case, we will take input from the user, and the condition mentioned in the switcher will be executed according to it. Let’s take an example:

Code:

a = int(input("Enter 1st Number:"))
b = int(input("Enter 2nd Number:"))
def xyz(x):
    switcher = {
        'addition':a+b,
        'multiplication':a*b,
        'subtraction':a-b,
        'division':a/b
    }
    return switcher.get(x,"Oops! Invalid Option")
result=xyz('multiplication')
print(result)

Output:

Arithmetic operations using switch case in python

We have written the above switch case program in python using switcher or also known as dictionary mapping. As we all know in the dictionary, we have key-value pairs. Similarly, here we have defined the case as a key, and the operation to that key is a value. In the above program, we have defined a function XYZ that is accepting x as an input. We have defined switched, and in the curly bracket, we have written multiple conditions. We are performing operations on two variables, a and b.

In the dictionary, we have to get a method; the get method takes two parameters, the first parameter will be a matching condition, and the second parameter is a statement that will be returned to the user if none of the conditions is satisfied. Suppose the user passed ‘addition’ as an x to the XYZ function, the get method will execute the operation about the ‘addition’ key. If the user enters anything that is not found in the switcher, then the second statement will be returned to the user, i.e. ‘Oops! Invalid Operation’. You can also pass the definition of another function in switcher keys.

Example #2

The below program takes input numbers and results into the corresponding month name. We have created a month’s class and defined a function switch case having an instance of the class, i.e. self. Using instance, we can access the attributes and properties of the classes. We have passed month_number as the second parameter that will accept the user input. Then we have a dictionary getattr method that has an instance, user input, and the default value.

Code:

class Months:
    def switchCase(self, month_number):
        default = "Oops! Wrong Input"
        return getattr(self, 'month_' + str(month_number), lambda: default)()
    def month_1(self):
        return "January"
    def month_2(self):
        return "February"
    def month_3(self):
        return "March"
    def month_4(self):
        return "April"
        def month_5(self):
            return "June"
result = Months()
print(result.switchCase(3))
print(result.switchCase(5))
print(result.switchCase(10))

Output:

Arithmetic operations using switch case in python

We are appending month_ with the user input integer number that will match corresponding defined methods in the switch case and return the month name in String. Then we have created the result object of the class Months, and using this object; we can access all the attributes and properties of the class. Now we have pass integer value from 1 to 5 to have the resulting month name and if pass other than 1 to 5 then getattr() will return default lambda function message ‘Oops! Wrong Input“.

Conclusion

As you have read till now, Python doesn’t have a switch case of its own, but we have created switch case conditions using switcher, and it works exactly like a switch case. A switch case is recommended instead of having too many nested if-else conditions. Too many nested conditions make program execution slow.

Recommended Article

This is a guide to Python Switch Case. Here we discuss the Introduction and its examples along with Code Implementation and Output. You can also go through our other suggested articles to learn more –

  1. Python Switch Statement
  2. Multiple Inheritance in Python
  3. Python Range Function
  4. List Method in Python

Can we do arithmetic operations in switch case?

Can we use arithmetic operators in switch case: Yes, We Can use we. To provide symbols in a case statement a single quote is used. To perform arithmetic operations, we create a case for each operator, for the matching operator, it will call the appropriate case statements and execute the statements.

How do you write arithmetic operations in Python?

Addition Operator : In Python, + is the addition operator. ... .
Subtraction Operator : In Python, – is the subtraction operator. ... .
Multiplication Operator : In Python, * is the multiplication operator. ... .
Division Operator : In Python, / is the division operator. ... .
Modulus Operator : In Python, % is the modulus operator..

What is switch case in python?

Python Switch Case is a selection control statement. The switch expression is evaluated once. The value of the expression is compared with the values of each case, if there is a match, the associated block of code is executed.

What are the arithmetic operators in Python explain with example?

Python Arithmetic Operators.