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.
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