Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 33 additions & 22 deletions Code/Python/Calculator-Working.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Program make a simple calculator
# Simple Calculator Program

# This function adds two numbers
def add(x, y):
Expand All @@ -12,43 +12,54 @@ def subtract(x, y):
def multiply(x, y):
return x * y

# This function divides two numbers
# This function divides two numbers (with error handling)
def divide(x, y):
if y == 0:
print("Error: Division by zero is not allowed.")
return None
return x / y


print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("===== Simple Calculator =====")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("=============================")

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

# check if choice is one of the four options
# check if choice is valid
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid number! Please enter valid numeric values.\n")
continue

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

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

elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
print(f"{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("Let's do next calculation? (yes/no): ")
result = divide(num1, num2)
if result is not None:
print(f"{num1} / {num2} = {result}")

# ask user for next calculation
next_calculation = input("Do you want to perform another calculation? (yes/no): ").lower()
if next_calculation == "no":
break

print("Exiting calculator... Goodbye!")
break
print()

else:
print("Invalid Input")
print("Invalid input! Please select a valid operation.\n")