-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.py
More file actions
82 lines (68 loc) · 2.13 KB
/
calculator.py
File metadata and controls
82 lines (68 loc) · 2.13 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
78
79
80
81
82
while True:
try:
num1 = float(input("Enter the first number: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
while True:
operator = input("Enter an operator (+, -, *, /): ")
if operator in ['+', '-', '*', '/']:
break
else:
print("Invalid operator. Please enter +, -, *, or /.")
while True:
try:
num2 = float(input("Enter the second number: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
# Perform the calculation
try:
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
result = num1 / num2
print(f"{num1} {operator} {num2} = {result}")
except ZeroDivisionError:
print("Cannot divide by zero")
def get_number(prompt: str) -> float:
while True:
value = input(prompt)
try:
return float(value)
except ValueError:
print("Please enter a valid number.")
def get_operator() -> str:
while True:
operator = input("Enter an operator (+, -, *, /): ")
if operator in {"+", "-", "*", "/"}:
return operator
print("Please enter a valid operator: +, -, *, /." )
def calculate(num1: float, operator: str, num2: float) -> float:
if operator == "+":
return num1 + num2
elif operator == "-":
return num1 - num2
elif operator == "*":
return num1 * num2
return num1 / num2
print("\nValidated calculator")
num1 = get_number("Enter the first number: ")
operator = get_operator()
num2 = get_number("Enter the second number: ")
result = calculate(num1, operator, num2)
print(f"{num1} {operator} {num2} = {result}")
print("\nValidated calculator with zero-division handling")
num1 = get_number("Enter the first number: ")
operator = get_operator()
num2 = get_number("Enter the second number: ")
try:
result = calculate(num1, operator, num2)
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print(f"{num1} {operator} {num2} = {result}")