Click here to Skip to main content
15,868,164 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I just want to know how these 2 line of codes work i dont understand at

calculator_function = opreations[opreation_function]
        answer = calculator_function(num_1, num_2)



i have posted the full code below on what have you tried area
its a basic calculator that i am learning on pycharm the code works perfectly its just these two lines i want to know how do they work

What I have tried:

def add(n1, n2):
    return n1 + n2

def subtract(n1, n2):
    return n1 - n2

def multiply(n1, n2):
    return n1 * n2

def divide(n1, n2):
    return n1 / n2

opreations = {"+": add, "-": subtract, "*": multiply, "/": divide}

def calculator():
    should_continue = True
    num_1 = float(input("What is The First Number: \n"))

    for symbols in opreations:
        print(symbols)

    while should_continue == True:

        opreation_function = input("Please select a operator to continue: \n")

        num_2 = float(input("What Is The Next Number: \n"))

        calculator_function = opreations[opreation_function]
        answer = round(calculator_function(num_1, num_2))
        print(f"{num_1} {opreation_function} {num_2} = {answer}")
        loop = True
        while loop == True:

            result = input(f"Type Y to continue with {answer} N to start new or Q to quit: \n").lower()

            if result == "y":
                num_1 = answer
                loop = False
            elif result == "n":
                loop = False
                should_continue = False
                calculator()
            elif result == "q":
                loop = False
                should_continue = False
                print("Good Bye :)")

calculator()
Posted
Updated 17-Jan-22 6:49am

1 solution

the variable opreations is a dictionary which contains the function characters as the keys, and the actual functions as the values. So when the user enters '+' the calculator_function will be set to point to the add function. and the next line:
Python
answer = round(calculator_function(num_1, num_2))

Will call that function.

You can see this in action by running the code through pdb — The Python Debugger — Python 3.10.2 documentation[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900