-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_calculator.py
More file actions
97 lines (81 loc) · 2.6 KB
/
simple_calculator.py
File metadata and controls
97 lines (81 loc) · 2.6 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import os
import sys
error_msg = '\n[!] ERROR: Invalid option. Please try again.\n'
error_msg2 = '\n[!] ERROR: Must be a positive integer.\n'
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:
raise ValueError("Cannot divide by zero.")
return a / b
def get_positive_input(prompt):
while True:
try:
value = float(input(prompt))
if not value.is_integer:
print(error_msg2)
continue
return value
except ValueError:
print(error_msg)
def user_input():
while True:
print("Please select an operation:")
print("[1] Add")
print("[2] Subtract")
print("[3] Multiply")
print("[4] Divide")
print("[5] Quit")
choice = input("Enter your choice (1-5): ")
if choice == "1":
a = get_positive_input("First Num: ")
b = get_positive_input("Second Num: ")
print("\nSum: {:0.2f}".format(add(a,b)))
break
elif choice == "2":
a = get_positive_input("First Num: ")
b = get_positive_input("Second Num: ")
print("\nDifference: {:0.2f}".format(subtract(a,b)))
break
elif choice == "3":
a = get_positive_input("First Num: ")
b = get_positive_input("Second Num: ")
print("\nProduct: {:0.2f}".format(multiply(a,b)))
break
elif choice == "4":
a = get_positive_input("First Num: ")
b = get_positive_input("Second Num: ")
try:
print("\nQuotient: {:0.2f}".format(divide(a,b)))
except ValueError as e:
print(e)
break
elif choice == "5" or choice == 'exit':
print("Thank you and have a great day!")
sys.exit()
else:
print(error_msg)
break
def main():
os.system('cls' if os.name == 'nt' else 'clear')
app_name = 'Simple Calculator'
print(f'{"-" * 48}')
print(f'{" "*10}{app_name}{" "*10}')
print(f'{"-" * 48}')
user_input()
while True:
response = input('\nDo you want to continue? (Y/N)')
if response == 'y' or response == 'Y':
main()
elif response == 'n' or response == 'N' or response == 'exit':
print('\nThank you and have a great day.\n')
sys.exit()
else:
print('\nError: Please select Y or N.\n')
continue
if __name__ == '__main__':
main()