Multiple Choice Functions

Author
Published

June 12, 2023

def sum(a,b):
    return a+b

def subtract(a,b):
    return a-b

def multiply(a,b):
    return a*b

def divide(a,b):
    return (a/b) if b!=0 else "Error"
a = 3
b = 2

task = "sum"

1. If-Else

def if_else(task):
    if task == "sum":
        return(sum(a,b))
    elif task == "subtract":
        return(subtract(a,b))
    elif task == "multiply":
        return(multiply(a,b))
    elif task == "divide":
        return(divide(a,b))
    else:
        return("Invalid task")

2. Function Dictionary

funDict = {"sum": sum, "subtract": subtract, "multiply": multiply, "divide": divide}

3. Match-Case

def match_case(task):
    match task:
        case "sum":
            return sum(a,b) 
        case "subtract":
            return subtract(a,b) 
        case "multiply":
            return multiply(a,b) 
        case "divide":
            return divide(a,b) 
        case default:
            return "Invalid task" 
print(if_else(task))
print(funDict[task](a,b))
print(match_case(task))
5
5
5