-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_calculator.py
More file actions
70 lines (53 loc) · 1.69 KB
/
simple_calculator.py
File metadata and controls
70 lines (53 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Simple Calculator (Improved Version)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return None
return a / b
def get_numbers():
while True:
try:
a = float(input("Enter Your First Number : "))
b = float(input("Enter Your Second Number : "))
return a, b
except ValueError:
print("❌ Invalid input! Please enter valid numbers.\n")
print("Choose an operation :")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
print("-" * 40)
while True:
try:
choice = int(input("Enter Choice : "))
if choice == 1:
a, b = get_numbers()
print(f"Sum of {a} and {b} = {add(a, b)}\n")
elif choice == 2:
a, b = get_numbers()
print(f"Subtraction of {a} and {b} = {subtract(a, b)}\n")
elif choice == 3:
a, b = get_numbers()
print(f"Multiplication of {a} and {b} = {multiply(a, b)}\n")
elif choice == 4:
a, b = get_numbers()
result = divide(a, b)
if result is None:
print("❌ Error: Cannot divide by zero.\n")
else:
print(f"Division of {a} and {b} = {result}\n")
elif choice == 5:
print("Calculator exited. Goodbye 👋")
break
else:
print("❌ Invalid choice. Please select between 1 and 5.\n")
print("-" * 40)
except ValueError:
print("❌ Invalid choice! Please enter a number.\n")