-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalc.py
More file actions
77 lines (58 loc) · 1.99 KB
/
calc.py
File metadata and controls
77 lines (58 loc) · 1.99 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
num, num2, total = 0, 0, 0
accepted_operators = {"+", "-", "*", "/", "%", "^", ""}
def get_input_number():
"""Returns valid numerical input from user."""
while(True):
try:
user_input = float(input("Please enter a number: "))
except ValueError:
print("That is not a valid number!")
else:
return user_input
def get_input_operator():
"""Returns valid mathematical operator from user."""
while(True):
operator = input("Please enter an operator (+, -, *, /, %, ^) or leave it blank to finish your calculation: ")
if operator in accepted_operators:
break
else:
print("That is not a valid operator!")
return operator
def check_divide_by_zero(operator, operand):
"""Checks if user is dividng by 0 and returns True if detected."""
if (operator == "/" and operand == 0):
return True
else:
return False
def perform_calculation(current_total, operator, operand):
"""Performs mathematical calculation based on number and operator params."""
new_total = 0
match operator:
case "+":
new_total = current_total + operand
case "-":
new_total = current_total - operand
case "*":
new_total = current_total * operand
case "/":
new_total = current_total / operand
case "%":
new_total = current_total % operand
case "^":
new_total = current_total ** operand
return new_total
total = get_input_number()
while(True):
operator = get_input_operator()
if operator == "":
break
input_num = 0
while(True):
input_num = get_input_number()
if (check_divide_by_zero(operator, input_num)):
print("Cannot divide by 0!")
else:
break
total = perform_calculation(total, operator, input_num)
print("Total: " + str(total))
print("Final total: ", str(total))