Showing posts with label switch case implementation in python. Show all posts
Showing posts with label switch case implementation in python. Show all posts

Tuesday, 9 January 2018

Switch case implementation in python

Example:

def calculator(operator, x, y):
    if operator == 'add':
        return x + y
    elif operator == 'sub':
        return x - y
    elif operator == 'mul':
        return x * y
    elif operator == 'div':
        return x / y
    else:
        return None

print(calculator('add',2,3))
print(calculator('div',6,2))
print(calculator('mod',4,2))

Output:

5
3.0

None


Example: by using dict

def calculator(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)()

print(calculator('add',2,3))
print(calculator('div',6,2))

print(calculator('mod',4,2))


Output:

5
3.0
None

Saturday, 9 September 2017

switch case implementation in python

Switch Case:

def switch(operator,x,y):
    if operator=='add':
        z=x+y
        print("the addition of",x,"and",y,"is: ",z)
    elif operator=='sub':
        z=x-y
        print("the subtraction of",x,"and",y,"is: ",z)
    elif operator=='mul':
        z=x*y
        print("the multiplication of",x,"and",y,"is: ",z)
    elif operator=='div':
        z=x/y
        print("the division of",x,"and",y,"is: ",z)
    else:
        print("operation failed")
switch('add',4,5)
switch('sub',4,5)
switch('mul',4,5)
switch('div',4,5)
switch('mod',4,5)

Output:

        
the addition of 4 and 5 is:  9
the subtraction of 4 and 5 is:  -1
the multiplication of 4 and 5 is:  20
the division of 4 and 5 is:  0.8

operation failed