-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic_calculator.py
More file actions
77 lines (55 loc) · 1.91 KB
/
dynamic_calculator.py
File metadata and controls
77 lines (55 loc) · 1.91 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
71
72
73
74
75
76
77
"""
Dynamic calculator supporting add, subtract, multiply, and divide operations.
Author: Chaitanya Dasadiya
GitHub: https://github.com/cdasadiya
LinkedIn: https://in.linkedin.com/in/chaitanya-dasadiya
"""
def add(a: float, b: float) -> float:
return a + b
def subtract(a: float, b: float) -> float:
return a - b
def multiply(a: float, b: float) -> float:
"""Return the product of two numbers."""
return a * b
def divide(a: float, b: float) -> float:
if b == 0:
raise ZeroDivisionError("Cannot divide by zero.")
return a / b
def get_number(prompt: str) -> float:
while True:
raw_value = input(prompt).strip()
try:
return float(raw_value)
except ValueError:
print("Invalid number. Please enter a valid numeric value.")
def run_calculator() -> None:
operations = {
"1": ("Addition", add),
"2": ("Subtraction", subtract),
"3": ("Multiplication", multiply),
"4": ("Division", divide),
}
print("Dynamic Calculator")
print("------------------")
while True:
print("\nChoose an operation:")
for key, (name, _) in operations.items():
print(f"{key}. {name}")
print("5. Exit")
choice = input("Enter your choice (1-5): ").strip()
if choice == "5":
print("Thank you for using Dynamic Calculator!")
break
if choice not in operations:
print("Invalid choice. Please select from 1 to 5.")
continue
num1 = get_number("Enter the first number: ")
num2 = get_number("Enter the second number: ")
operation_name, operation_func = operations[choice]
try:
result = operation_func(num1, num2)
print(f"Result of {operation_name}: {result}")
except ZeroDivisionError as error:
print(error)
if __name__ == "__main__":
run_calculator()