Simple Calculator

Mosh gave me an exercise to create a simple calculator, Ill admit this is not all my own work ( wished I could say it was) Im trying to add a while loop so that I can ask user if they would like to do another calculation.

Here is the code…..

def add(x, y):

return x + y

def subtract(x,y):

return x - y

def devide(x, y):

return x / y

def multiply(x, y):

return x \* y

num1 = float(input("Enter First Number: "))

num2 = float(input("Enter Second Number: "))

print (“select operation.”)

print (“1, Add”)

print (“2, Subtract”)

print (“3, Devide”)

print (“4, Multiply”)

choice = input(“Enter Choice (1/2/3/4):”)

if choice == “1”:

print(num1, "+" ,num2, "=", add(num1,num2))

elif choice == “2”:

print(num1, "-" ,num2, "=", subtract(num1,num2))

elif choice == “3”:

print(num1, "/" ,num2, "=", devide(num1,num2))

elif choice == “4”:

print(num1, "\*" , num2, "=", multiply(num1,num2))

else:

print("invalid option")

You want to use an infinite while loop or a Boolean variable that will change based on user input.

while true:
#all the code from num1 to (“invalid option”)

or if you want to use a variable

isCalculating = true
while isCalculating:
// code

     // another input statement here to stop calculating
    // set isCalculating to false
    // print (“Good bye”)

Either one of these works and I’m sure there are more ways to do this.

Hi there,

i added the while loop at the end i just didnt like that many elifs so to be honest i asked chatgpt to give me a cleaner way and it mentioned dictionary of function here is the result i think its much better

import math

def add(x, y):

return x + y

def subtract(x, y):

return x - y

def divide(x, y):

if y == 0:

    return "Cannot divide by zero"

return x / y

def multiply(x, y):

return x \* y

while True:

num1 = float(input("Enter First Number: "))

num2 = float(input("Enter Second Number: "))



print("Select Operation.")

print("1. Add")

print("2. Subtract")

print("3. Divide")

print("4. Multiply")



choice = input("Enter choice (1/2/3/4): ")



operations = {

    "1": add,

    "2": subtract,

    "3": divide,

    "4": multiply

}



if choice in operations:

    print("Result:", operations\[choice\](num1, num2))

else:

    print("Invalid option")



again = input("Do you wan to calculate again? (y/n): ").lower()



if again != "y":

    print("Calculator Closed")

    break