Skip to content

Commit ba99e78

Browse files
authored
Create calculator_with_history.py
creating new program
1 parent 1af92ff commit ba99e78

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

calculator_with_history.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Calculator with history
2+
HISTORY_FILE = "history.txt"
3+
4+
def show_history():
5+
try:
6+
with open(HISTORY_FILE, 'r') as file:
7+
lines = file.readlines()
8+
if len(lines) == 0:
9+
print("No history found")
10+
else:
11+
print("\n--- Calculation History ---")
12+
for line in reversed(lines): # show most recent first
13+
print(line.strip())
14+
except FileNotFoundError:
15+
print("No history file found yet")
16+
17+
def clear_history():
18+
with open(HISTORY_FILE, 'w') as file:
19+
pass
20+
print("History is cleared")
21+
22+
def save_to_history(eq, result):
23+
with open(HISTORY_FILE, 'a') as file:
24+
file.write(eq + " = " + str(result) + "\n")
25+
26+
def calculator(user_input):
27+
parts = user_input.split()
28+
if len(parts) != 3:
29+
print("Invalid input! Use syntax: number operator number")
30+
return
31+
32+
try:
33+
n1 = float(parts[0])
34+
n2 = float(parts[2])
35+
except ValueError:
36+
print("Invalid numbers!")
37+
return
38+
39+
op = parts[1]
40+
41+
if op == '+':
42+
result = n1 + n2
43+
elif op == '-':
44+
result = n1 - n2
45+
elif op == '*':
46+
result = n1 * n2
47+
elif op == '/':
48+
if n2 == 0:
49+
print("Error: Division by zero")
50+
return
51+
result = n1 / n2
52+
else:
53+
print("Invalid operator! Use + - * /")
54+
return
55+
56+
# if result has no decimals, make it integer
57+
if int(result) == result:
58+
result = int(result)
59+
60+
print("Result:", result)
61+
save_to_history(user_input, result)
62+
63+
def main():
64+
print("------- Welcome to Simple Calculator with History -------")
65+
while True:
66+
user_input = input("\nEnter calculation using ( +, - , *, / ) or command (history, clear, exit): ").strip().lower()
67+
if user_input == 'exit':
68+
print("Thank you for using the calculator!")
69+
break
70+
elif user_input == 'history':
71+
show_history()
72+
elif user_input == 'clear':
73+
clear_history()
74+
else:
75+
calculator(user_input)
76+
77+
main()

0 commit comments

Comments
 (0)