ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
ဒီ Exercise Set က Exercise Set 1 ထက် တစ်ဆင့်တက်ပြီး OOP (classes), error handling, file handling, နဲ့ comprehensions စတဲ့ Intermediate/Advanced chapter concept များကို ပေါင်းစပ်ပြီး လက်တွေ့ solve ကြည့်ရန်ပါ။ Real project တွေမှာ concept တစ်ခုတည်းနဲ့ ပြီးလေ့မရှိဘဲ class, exception, file I/O စတာတွေ အတူတူ ပေါင်းသုံးရတတ်ပါတယ်။ ဒီအတွက် ဒီ tasks တွေက အဲဒီလို real-world scenario နဲ့ ပိုနီးစပ်အောင် design လုပ်ထားပါတယ်။ ကိုယ်တိုင် ဖြေရှင်းပြီး run လုပ်ကြည့်တာက Debugging skill ကိုပါ ထပ်မံ မြှင့်တင်ပေးပါလိမ့်မယ်။
လေ့ကျင့်ခန်းများ
Task 1: BankAccount class တစ်ခု ရေးပါ - balance attribute ရှိရမယ်၊ deposit() နဲ့ withdraw() method နှစ်ခု ရှိရမယ်၊ balance ထက် ပိုပြီး withdraw ကြိုးစားရင် custom exception InsufficientFundsError ကို raise လုပ်ပါ။ Task 2: try-except-finally သုံးပြီး text file တစ်ခုကို ဖတ်ကြည့်ပါ - file မရှိရင် FileNotFoundError ကို catch လုပ်ပြီး friendly message တစ်ခု print လုပ်ပါ၊ ရှိမရှိ finally block က "Read attempt finished" ဆိုတာကိုတော့ ဘယ်လိုပဲဖြစ်ဖြစ် print လုပ်ပါ။ Task 3: dictionary comprehension သုံးပြီး word list တစ်ခုကနေ {word: length} ပုံစံ dictionary တစ်ခု ဖန်တီးပါ၊ ပြီးရင် ရလာတဲ့ dictionary ကို length အလိုက် sort လုပ်ပြီး print ပါ။
Code နမူနာ
# Task 1: BankAccount with custom exception
class InsufficientFundsError(Exception):
pass
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError("Not enough balance!")
self.balance -= amount
acc = BankAccount(1000)
acc.deposit(500)
try:
acc.withdraw(2000)
except InsufficientFundsError as e:
print(f"Error: {e}")
finally:
print(f"Current balance: {acc.balance}")
# Task 2: safe file read
try:
with open("notes.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found, please check the filename.")
finally:
print("Read attempt finished")
# Task 3: dict comprehension + sort
words = ["python", "is", "fun", "and", "powerful"]
word_lengths = {w: len(w) for w in words}
sorted_words = dict(sorted(word_lengths.items(), key=lambda item: item[1]))
print(sorted_words)Task အားလုံး မှန်ကန်စွာ ဖြေရှင်းနိုင်ရင် withdraw error message + balance, file-read result (or friendly error), နဲ့ length အလိုက် sort လုပ်ထားတဲ့ dictionary တို့ကို output မှာ တွေ့ရမှာပါ။၅ မိနစ် စမ်းကြည့်
Timer 10 မိနစ် သတ်မှတ်ပြီး Task 1 ရဲ့ BankAccount class ကို ကိုယ်တိုင် code ရေးကြည့်ပါ - custom exception message ကို ကိုယ်ပိုင် text နဲ့ ပြောင်းရေးကြည့်ပါ။
သတိလေးတစ်ချက်
Custom exception တွေဖန်တီးတဲ့အခါ built-in exception name တွေနဲ့ မထပ်အောင် သတိထားပါ၊ ပြီးတော့ finally block ကို resource cleanup (file close, connection close) အတွက် အမြဲသုံးအပ်ပါတယ်။