Hi guys, I am relatively new to Python and have been working on a calculator application. It is relatively simple, but I would like to share it with everyone here in the group. I hope that there is someone in Daniweb who can guide me through Python.
As I read about Python, it is among the top three programming languages, and has many areas of use.
My background is in Electrical engineering, and I hope to use Python for some purpose in electrical engineering.
Please feel free to make any suggestions or improvements to the code.

# Program make a simple calculator

# This function adds two numbers
def add(x, y):
    return x + y

# This function subtracts two numbers
def subtract(x, y):
    return x - y

# This function multiplies two numbers
def multiply(x, y):
    return x * y

# This function divides two numbers
def divide(x, y):
    return x / y


print("Select your operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
    # take input from the user
    choice = input("Enter your choice(1/2/3/4): ")

    # check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter the first number: "))
        num2 = float(input("Enter the second number: "))

        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))

        elif choice == '2':
            print(num1, "-", num2, "=", subtract(num1, num2))

        elif choice == '3':
            print(num1, "*", num2, "=", multiply(num1, num2))

        elif choice == '4':
            print(num1, "/", num2, "=", divide(num1, num2))

        # check if user wants another calculation
        # break the while loop if answer is no
        next_calculation = input("Wanna do another calculation? (y/n): ")
        if next_calculation == "no":
          break

    else:
        print("Invalid Input")

Recommended Answers

All 2 Replies

Nice to see a new face. While I am far from being a Python pro I should be able to help with the simpler stuff. Welcome to Daniweb and thanks for sharing.

It looks like the code was taken from here but it also appears in lots of other places such as here or here.

Please always give credit where credit is due when copying/pasting someone else's code. Otherwise, it's code theft. While we have a community rule against copying/pasting from elsewhere for copyright reasons, I think it's fine in this case because this specific snippet was found soooooo many places around the web that it's probably public domain at this point.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.