|
| 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