پروژه: ماشینحساب پیشرفته
پروژه عملی: ساخت ماشینحساب کامل با کلاس، استثنا و توابع
پروژه ماشینحساب
در این پروژه، همه چیزهایی که یاد گرفتید را در قالب یک ماشینحساب کامل به کار میبندیم.
ویژگیها
- چهار عمل اصلی
- توان و جذر
- حافظه (Memory)
- تاریخچه عملیات
- مدیریت خطا
کد کامل
class Calculator:
"""ماشینحساب پیشرفته."""
def __init__(self):
self.memory = 0
self.history = []
def add(self, a, b):
result = a + b
self._log(f"{a} + {b}", result)
return result
def subtract(self, a, b):
result = a - b
self._log(f"{a} - {b}", result)
return result
def multiply(self, a, b):
result = a * b
self._log(f"{a} × {b}", result)
return result
def divide(self, a, b):
if b == 0:
raise ValueError("تقسیم بر صفر!")
result = a / b
self._log(f"{a} ÷ {b}", result)
return result
def power(self, a, b):
result = a ** b
self._log(f"{a} ^ {b}", result)
return result
def sqrt(self, a):
if a < 0:
raise ValueError("جذر عدد منفی!")
import math
result = math.sqrt(a)
self._log(f"√{a}", result)
return result
def memory_store(self, value):
self.memory = value
def memory_recall(self):
return self.memory
def memory_clear(self):
self.memory = 0
def _log(self, operation, result):
self.history.append(f"{operation} = {result}")
def show_history(self):
for entry in self.history:
print(entry)
استفاده
calc = Calculator()
print(calc.add(10, 5)) # 15
print(calc.multiply(4, 3)) # 12
print(calc.divide(20, 4)) # 5.0
print(calc.power(2, 10)) # 1024
# حافظه
calc.memory_store(100)
print(calc.memory_recall()) # 100
# تاریخچه
calc.show_history()
چیزهایی که استفاده کردیم
- ✅ کلاس و شیگرایی
- ✅ متدها و ویژگیها
- ✅ مدیریت خطا (raise)
- ✅ import ماژول
- ✅ Docstring
این مبحث بخشی از دوره آموزش کامل پایتون است.