top of page

Create A Calculator System in Python

Updated: Mar 7, 2023



The following is the code of a simple calculator system written with PYTHON. As always, I use Pycharm community edition to write the program. There are many other IDE to choose from, but I always feel more comfortable coding on Pycharm. The code here can be further improved and customized depending on personal peference.


The first section of the code is to write the function of four calculating formula.

Then we move on to write a loop where user can enter operation method and numbers. Inside the while loop there are there "if statements". The first one is to identify correct input information; the second oneis to ask whether the user would like to use the calculator; the third one is to identify which formula to run.




def add(x, y):
    return x + y

def subtract(x,y):
    return x - y

def divide(x,y):
    return x/y

def multiply(x,y):
    return x*y

while True:
    print("Welcome to Haruki Robotics Lab! Please Select operation: ")
    print("1.Add\n2.Subtract\n3.Multiply\n4.Divide")

    choice = input("Enter the corresponding number: ")
    if choice in ("1" , "2" , "3" , "4"):  #()

        firstNum = int(input('Enter the first number: '))
        secondNum = int(input('Enter the second number: '))

        if choice == "1":
            result = add(firstNum,secondNum)
            print(firstNum, "+", secondNum, "=", result)
        elif choice == "2":
            result = subtract(firstNum,secondNum)
            print(firstNum, "-", secondNum, "=", result)
        elif choice == "4":
            result = divide(firstNum,secondNum)
            print(firstNum, "/", secondNum, "=", result)
        elif choice == "3":
            result = multiply(firstNum,secondNum)
            print(firstNum, "*", secondNum, "=", result)

        option =input("Want to continue (yes/no)?")
        if option == "no":
            break

    else: print('Invalid Input')




Comentários


bottom of page