-
Notifications
You must be signed in to change notification settings - Fork 1
/
simple_calculator.py
53 lines (43 loc) · 1.08 KB
/
simple_calculator.py
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
# Calculator operations
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:
print("Cannot divide by 0!")
return None
return a / b
# Operation functions dict
operations = {
1: add,
2: subtract,
3: multiply,
4: divide
}
def calculate():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input_number("Enter choice(1-4): ")
num1 = input_number("Enter first number: ")
num2 = input_number("Enter second number: ")
func = operations.get(choice)
if func:
result = func(num1, num2)
if result is not None:
print(result)
else:
print("Invalid operation")
def input_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("Invalid input. Please enter a number")
continue
calculate()