-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculatorpython.py
More file actions
472 lines (386 loc) · 16.4 KB
/
Copy pathCalculatorpython.py
File metadata and controls
472 lines (386 loc) · 16.4 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
"""
╔══════════════════════════════════════════════════════════╗
║ PYTHON CALCULATOR APPLICATION ║
║ Basic + Scientific | History | File Export ║
╚══════════════════════════════════════════════════════════╝
A beginner-friendly yet professionally structured calculator
supporting basic arithmetic, scientific functions, history
tracking, and saving results to a text file.
"""
import math
import os
from datetime import datetime
# ── Globals ──────────────────────────────────────────────
history = [] # Stores every calculation performed this session
HISTORY_FILE = "calc_history.txt"
# ════════════════════════════════════════════════════════
# DISPLAY HELPERS
# ════════════════════════════════════════════════════════
def clear_screen():
"""Clear the terminal for a cleaner UI."""
os.system("cls" if os.name == "nt" else "clear")
def separator(char="─", width=54):
"""Print a horizontal divider line."""
print(char * width)
def welcome_screen():
"""Display the welcome banner when the program starts."""
clear_screen()
print()
separator("═")
print(" ██████╗ █████╗ ██╗ ██████╗")
print(" ██╔════╝██╔══██╗██║ ██╔════╝")
print(" ██║ ███████║██║ ██║ ")
print(" ██║ ██╔══██║██║ ██║ ")
print(" ╚██████╗██║ ██║███████╗╚██████╗")
print(" ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═════╝")
separator("═")
print(" Python Calculator | v2.0")
print(" Basic + Scientific | History | Export")
separator("═")
print()
input(" Press ENTER to start...")
def print_menu():
"""Print the main menu."""
clear_screen()
separator("═")
print(" CALCULATOR MENU")
separator("═")
print(" BASIC OPERATIONS")
print(" 1. Addition (+)")
print(" 2. Subtraction (−)")
print(" 3. Multiplication (×)")
print(" 4. Division (÷)")
print(" 5. Modulus (%)")
print(" 6. Power (xⁿ)")
separator()
print(" SCIENTIFIC OPERATIONS")
print(" 7. Square Root (√x)")
print(" 8. Logarithm (log/ln)")
print(" 9. Trigonometry (sin/cos/tan)")
print(" 10. Factorial (n!)")
print(" 11. Absolute Value (|x|)")
separator()
print(" HISTORY & TOOLS")
print(" 12. View History")
print(" 13. Save History to File")
print(" 14. Clear History")
separator()
print(" 0. Exit")
separator("═")
# ════════════════════════════════════════════════════════
# INPUT HELPERS
# ════════════════════════════════════════════════════════
def get_number(prompt=" Enter number: "):
"""
Safely read a float from the user.
Keeps asking until a valid number is entered.
"""
while True:
try:
return float(input(prompt))
except ValueError:
print(" ⚠ Invalid input — please enter a numeric value.\n")
def get_two_numbers():
"""Convenience wrapper: read two operands."""
a = get_number(" Enter first number : ")
b = get_number(" Enter second number: ")
return a, b
# ════════════════════════════════════════════════════════
# HISTORY HELPERS
# ════════════════════════════════════════════════════════
def record(expression: str, result):
"""
Append a calculation to the in-memory history list.
Each entry carries a timestamp for the saved file.
"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
history.append({"time": timestamp, "expr": expression, "result": result})
def show_history():
"""Display every calculation made this session."""
clear_screen()
separator("═")
print(" CALCULATION HISTORY")
separator("═")
if not history:
print(" No calculations yet.")
else:
for i, entry in enumerate(history, 1):
print(f" {i:>3}. {entry['expr']} = {entry['result']}")
separator("═")
input("\n Press ENTER to return to menu...")
def save_history():
"""Write the full history to a text file on disk."""
if not history:
print("\n Nothing to save yet.")
input(" Press ENTER to continue...")
return
with open(HISTORY_FILE, "w", encoding="utf-8") as f:
f.write("PYTHON CALCULATOR — SESSION HISTORY\n")
f.write(f"Saved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write("=" * 54 + "\n")
for i, entry in enumerate(history, 1):
f.write(f"{i:>3}. [{entry['time']}] "
f"{entry['expr']} = {entry['result']}\n")
f.write("=" * 54 + "\n")
f.write(f"Total calculations: {len(history)}\n")
print(f"\n ✔ History saved to '{HISTORY_FILE}'")
input(" Press ENTER to continue...")
def clear_history():
"""Wipe the in-memory history after confirmation."""
confirm = input("\n Clear all history? (y/n): ").strip().lower()
if confirm == "y":
history.clear()
print(" ✔ History cleared.")
else:
print(" Cancelled.")
input(" Press ENTER to continue...")
# ════════════════════════════════════════════════════════
# BASIC OPERATIONS
# ════════════════════════════════════════════════════════
def add(a, b):
"""Return the sum of a and b."""
return a + b
def subtract(a, b):
"""Return a minus b."""
return a - b
def multiply(a, b):
"""Return the product of a and b."""
return a * b
def divide(a, b):
"""
Return a divided by b.
Raises ZeroDivisionError if b is 0.
"""
if b == 0:
raise ZeroDivisionError("Cannot divide by zero.")
return a / b
def modulus(a, b):
"""
Return the remainder of a ÷ b.
Raises ZeroDivisionError if b is 0.
"""
if b == 0:
raise ZeroDivisionError("Cannot compute modulus with zero divisor.")
return a % b
def power(a, b):
"""Return a raised to the power b."""
return a ** b
# ════════════════════════════════════════════════════════
# SCIENTIFIC OPERATIONS
# ════════════════════════════════════════════════════════
def square_root(a):
"""
Return the square root of a.
Raises ValueError for negative inputs.
"""
if a < 0:
raise ValueError("Square root of a negative number is not real.")
return math.sqrt(a)
def logarithm():
"""
Compute log base-10 or natural log (ln) based on user choice.
Raises ValueError for non-positive inputs.
"""
print("\n Logarithm type:")
print(" 1. Log base-10 (log₁₀)")
print(" 2. Natural log (ln / logₑ)")
choice = input(" Choose (1/2): ").strip()
a = get_number(" Enter number: ")
if a <= 0:
raise ValueError("Logarithm is undefined for zero or negative numbers.")
if choice == "1":
result = math.log10(a)
expr = f"log₁₀({a})"
else:
result = math.log(a)
expr = f"ln({a})"
return expr, result
def trigonometry():
"""
Compute sin, cos, or tan of an angle.
User can choose degrees or radians.
Returns (expression_string, result).
"""
print("\n Trig function:")
print(" 1. Sine (sin)")
print(" 2. Cosine (cos)")
print(" 3. Tangent (tan)")
func_choice = input(" Choose (1/2/3): ").strip()
print("\n Angle unit:")
print(" 1. Degrees")
print(" 2. Radians")
unit_choice = input(" Choose (1/2): ").strip()
angle = get_number(" Enter angle: ")
# Convert to radians if degrees were given
rad = math.radians(angle) if unit_choice == "1" else angle
unit_label = "°" if unit_choice == "1" else " rad"
if func_choice == "1":
result = math.sin(rad)
expr = f"sin({angle}{unit_label})"
elif func_choice == "2":
result = math.cos(rad)
expr = f"cos({angle}{unit_label})"
elif func_choice == "3":
# tan is undefined at 90°, 270°, etc.
if unit_choice == "1" and angle % 180 == 90:
raise ValueError("tan is undefined at 90° + 180°·n.")
result = math.tan(rad)
expr = f"tan({angle}{unit_label})"
else:
raise ValueError("Invalid trig function choice.")
return expr, result
def factorial(a):
"""
Return n! for a non-negative integer a.
Raises ValueError for negatives or non-integers.
"""
if a < 0:
raise ValueError("Factorial is undefined for negative numbers.")
if a != int(a):
raise ValueError("Factorial requires a whole number.")
return math.factorial(int(a))
def absolute_value(a):
"""Return the absolute value of a."""
return abs(a)
# ════════════════════════════════════════════════════════
# OPERATION RUNNERS (connect menu → functions → history)
# ════════════════════════════════════════════════════════
def run_basic(op_number):
"""
Handle menu options 1–6 (basic arithmetic).
op_number maps to the operator chosen.
"""
ops = {
1: ("+", add),
2: ("−", subtract),
3: ("×", multiply),
4: ("÷", divide),
5: ("%", modulus),
6: ("**", power),
}
symbol, func = ops[op_number]
print(f"\n {'─'*40}")
a, b = get_two_numbers()
try:
result = func(a, b)
# Format cleanly: drop unnecessary decimal for whole results
display = int(result) if isinstance(result, float) and result.is_integer() else round(result, 10)
expr = f"{a} {symbol} {b}"
print(f"\n ✔ Result: {expr} = {display}")
record(expr, display)
except ZeroDivisionError as e:
print(f"\n ✘ Math Error: {e}")
except Exception as e:
print(f"\n ✘ Error: {e}")
input("\n Press ENTER to continue...")
def run_sqrt():
"""Handle Square Root (menu 7)."""
print("\n ──────────────────────────────────────────")
a = get_number(" Enter number: ")
try:
result = square_root(a)
display = round(result, 10)
expr = f"√({a})"
print(f"\n ✔ Result: {expr} = {display}")
record(expr, display)
except ValueError as e:
print(f"\n ✘ Error: {e}")
input("\n Press ENTER to continue...")
def run_log():
"""Handle Logarithm (menu 8)."""
print("\n ──────────────────────────────────────────")
try:
expr, result = logarithm()
display = round(result, 10)
print(f"\n ✔ Result: {expr} = {display}")
record(expr, display)
except ValueError as e:
print(f"\n ✘ Error: {e}")
input("\n Press ENTER to continue...")
def run_trig():
"""Handle Trigonometry (menu 9)."""
print("\n ──────────────────────────────────────────")
try:
expr, result = trigonometry()
display = round(result, 10)
print(f"\n ✔ Result: {expr} = {display}")
record(expr, display)
except ValueError as e:
print(f"\n ✘ Error: {e}")
input("\n Press ENTER to continue...")
def run_factorial():
"""Handle Factorial (menu 10)."""
print("\n ──────────────────────────────────────────")
a = get_number(" Enter number: ")
try:
result = factorial(a)
expr = f"{int(a)}!"
print(f"\n ✔ Result: {expr} = {result}")
record(expr, result)
except ValueError as e:
print(f"\n ✘ Error: {e}")
input("\n Press ENTER to continue...")
def run_abs():
"""Handle Absolute Value (menu 11)."""
print("\n ──────────────────────────────────────────")
a = get_number(" Enter number: ")
result = absolute_value(a)
expr = f"|{a}|"
print(f"\n ✔ Result: {expr} = {result}")
record(expr, result)
input("\n Press ENTER to continue...")
# ════════════════════════════════════════════════════════
# MAIN LOOP
# ════════════════════════════════════════════════════════
def main():
"""
Entry point.
Displays the welcome screen, then loops through the
menu until the user selects option 0 (Exit).
"""
welcome_screen()
while True:
print_menu()
choice = input(" Enter your choice: ").strip()
# ── Basic operations ──────────────────────────
if choice in ("1", "2", "3", "4", "5", "6"):
run_basic(int(choice))
# ── Scientific operations ─────────────────────
elif choice == "7":
run_sqrt()
elif choice == "8":
run_log()
elif choice == "9":
run_trig()
elif choice == "10":
run_factorial()
elif choice == "11":
run_abs()
# ── History & tools ───────────────────────────
elif choice == "12":
show_history()
elif choice == "13":
save_history()
elif choice == "14":
clear_history()
# ── Exit ──────────────────────────────────────
elif choice == "0":
clear_screen()
separator("═")
print(" Thanks for using Python Calculator!")
print(f" Total calculations this session: {len(history)}")
if history:
save_prompt = input("\n Save history before exiting? (y/n): ").strip().lower()
if save_prompt == "y":
save_history()
separator("═")
print()
break
else:
print("\n ⚠ Invalid choice. Please enter a number from the menu.")
input(" Press ENTER to continue...")
# ════════════════════════════════════════════════════════
# PROGRAM ENTRY POINT
# ════════════════════════════════════════════════════════
if __name__ == "__main__":
main()