-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator_with_history.py
More file actions
92 lines (70 loc) · 2.05 KB
/
calculator_with_history.py
File metadata and controls
92 lines (70 loc) · 2.05 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
import os
import re
HISTORY_FILE = "history.txt"
def show_history():
if not os.path.exists(HISTORY_FILE):
print("No history found!")
return
with open(HISTORY_FILE, 'r') as file:
lines = file.readlines()
if not lines:
print("No history found!")
else:
for line in reversed(lines):
print(line.strip())
def clear_history():
with open(HISTORY_FILE, 'w'):
pass
print("History cleared.")
def saveto_history(equation, result):
with open(HISTORY_FILE, 'a') as file:
file.write(f"{equation} = {result}\n")
def calculate(user_input):
# Allow input like 2+2 by adding spaces automatically
user_input = re.sub(r'(\d)([+\-*/])(\d)', r'\1 \2 \3', user_input)
parts = user_input.split()
if len(parts) != 3:
print("Invalid input! USE FORMAT: number operator number (i.e. 8 + 8)")
return
try:
num1 = float(parts[0])
op = parts[1]
num2 = float(parts[2])
except ValueError:
print("Invalid numbers.")
return
if op == "+":
result = num1 + num2
elif op == "-":
result = num1 - num2
elif op == "*":
result = num1 * num2
elif op == "/":
if num2 == 0:
print("Cannot divide by zero.")
return
result = num1 / num2
else:
print("Invalid operator. USE ONLY +, -, *, /.")
return
if result.is_integer():
result = int(result)
print("RESULT:", result)
saveto_history(user_input, result)
def main():
print("--- SIMPLE CALCULATOR (type history, clear or exit) ---")
while True:
user_input = input(
"Enter calculation (+ - * /) OR command (history, clear, exit): "
).strip().lower()
if user_input == 'exit':
print("Goodbye!")
break
elif user_input == 'history':
show_history()
elif user_input == 'clear':
clear_history()
else:
calculate(user_input)
if __name__ == "__main__":
main()