2024-08-02: 6. Calculator

My simple calculator.

# def calculator function
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


# create a dictionary contains =-*/ operations
operations = {
    '+': add,
    '-': subtract,
    '*': multiply,
    '/': divide
}


# start build this calculator
def calculator():
    # input 1st number
    num1 = float(input("What's the 1st number: "))

    yesno = True

    # start while loop
    while yesno:
        # print operation symbols(+-*/) for choose
        for key in operations:
            print(key)

        # choose operation
        symbol = input("pick a operation from symbols list above: ")

        # input 2nd number
        num2 = float(input("What's the next number: "))

        # calculation
        answer = operations[symbol](num1, num2)

        # print answer
        print(f"{num1} {symbol} {num2} = {answer}")

        # let user choose if continue with the answer
        if input(f"Input 'y' if you want continue with {answer}; or 'n' if you want start freshly.\n") == "y":
            # assign the answer value to num1
            num1 = answer
        else:
            # jump out from while loop
            yesno = False

            # call calculator itself 
            calculator()


# start run this calculator
calculator()