ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
စားသောက်ဆိုင်တစ်ဆိုင်မှာ စားပွဲထိုးနဲ့ မီးဖိုချောင် ခွဲထားသလိုပဲ calculator ကိုလည်း နှစ်ပိုင်း ခွဲပါမယ်။ စားပွဲထိုး (interface) က customer ဆီက order ကို ယူ၊ မရှင်းရင် ပြန်မေး၊ ဟင်းကို ချပေးပါတယ်။ မီးဖိုချောင် (logic) က order စာရွက်ကိုပဲ ကြည့်ပြီး ဟင်းချက်ပါတယ်။ Customer နဲ့ တိုက်ရိုက် စကားမပြောပါဘူး။
ဒီလို ခွဲထားရင် မီးဖိုချောင်ကို customer မလိုဘဲ စမ်းလို့ရပါတယ်။ "10 / 0" ဆိုတဲ့ order စာရွက်ပေးပြီး မှန်မှန်ကန်ကန် ငြင်းလား စစ်လိုက်ရုံပါပဲ။ စားပွဲထိုးကို terminal ကနေ GUI ဒါမှမဟုတ် web page အဖြစ် ပြောင်းချင်ရင်လည်း မီးဖိုချောင်ကို မထိရပါဘူး။
Problem → Why → Solution
ပြဿနာ: eval() တစ်ကြောင်းတည်း calculator
Calculator ရေးဖို့ အတိုဆုံးနည်းက print(eval(input("> "))) ပါ။ "5 + 3" ရိုက်ရင် 8 ရလို့ ပထမတော့ အံ့သြစရာ ကောင်းပါတယ်။ ဒါပေမဲ့ eval() က Python code ဘယ်ဟာကိုမဆို run ပါတယ်။ User က __import__('os').remove('data.db') လို့ ရိုက်ရင် file ကို ဖျက်ပစ်မှာ ဖြစ်ပြီး ဒီ calculator ကို web form နောက်ကွယ်မှာ ထားလိုက်ရင် server ကို အဝေးကနေ ထိန်းချုပ်ခွင့် ပေးလိုက်သလို ဖြစ်ပါတယ်။
eval() မသုံးတဲ့ ရိုးရိုး calculator မှာတောင် တခြား ပြဿနာ နှစ်ခု ရှိနိုင်ပါတယ်။ input() နဲ့ print() က calculation code ထဲမှာ ရောနေရင် test လုပ်လို့ မရပါဘူး။ divide() က error ဖြစ်တဲ့အခါ "Error! Division by zero." ဆိုတဲ့ string ကို ပြန်ပေးရင် caller က ရလဒ်ကို number လို့ ယူပြီး ဆက်တွက်တဲ့အခါ TypeError ဖြစ်ပါတယ်။
print(eval(input("> "))) # "5 + 3" -> 8 ... and also any Python code
def divide(a, b):
if b == 0:
return "Error! Division by zero." # a str where a number was expected
return a / b
total = divide(10, 0) + 1 # TypeError: can only concatenate str (not "int") to strဘာကြောင့် ဒီလိုဖြစ်တာလဲ
eval() က input ကို ဂဏန်းသင်္ချာ expression လို့ မမြင်ဘဲ Python program အပြည့်အစုံလို့ မြင်ပါတယ်။ "ဘာကို ခွင့်ပြုမလဲ" ဆိုတဲ့ စာရင်း (allowlist) မရှိရင် user က ဘာမဆို run နိုင်ပါတယ်။ Error ကို string အဖြစ် return လုပ်တာကလည်း success နဲ့ failure ကို type တစ်ခုတည်းထဲ ရောထည့်တာပါ။ Exception ကို raise လုပ်ရင်တော့ caller က ignore လုပ်လို့ မရတော့ပါဘူး။
Core concept: logic နဲ့ interface ကို ခွဲပါ
Project lesson ရဲ့ အဓိကသင်ခန်းစာက ဂဏန်းတွက်တာ မဟုတ်ပါဘူး။ Program ကို အလွှာတွေ ခွဲတာပါ။ Logic အလွှာက string ကို လက်ခံပြီး ရလဒ် ဒါမှမဟုတ် exception ကို ပြန်ပေးပါတယ်။ Interface အလွှာက user ဆီက line ကို ဖတ်၊ logic ကို ခေါ်၊ ရလဒ် ဒါမှမဟုတ် error message ကို ပြပါတယ်။ အလွှာတစ်ခုစီရဲ့ တာဝန်ကို အောက်ပါအတိုင်း ခွဲထားပါတယ်။
Two layers of the calculator
----------------------------
user types "15 / 4"
|
+--------v--------------------- interface (run_session) ---+
| read(prompt) -> line ; 'q' / 'help' handled here |
| try: write("= " + evaluate_line(line)) |
| except CalculatorError: write("Error: ...") |
+--------|--------------------------------------------------+
v
+------------------------------- logic (pure functions) ----+
| evaluate_line -> split into 3 parts |
| parse_number -> float or CalculatorError |
| calculate -> OPERATIONS[op](a, b) or CalculatorError |
+-----------------------------------------------------------+၁။ Operator allowlist
OPERATIONS dict က "+" ကို operator.add နဲ့၊ "/" ကို operator.truediv နဲ့ ချိတ်ထားပါတယ်။ Dict ထဲမှာ မရှိတဲ့ symbol ကို ငြင်းလို့ user က ခွင့်ပြုထားတာထက် ပိုလုပ်လို့ မရပါဘူး။ Operator အသစ်ထည့်ချင်ရင် dict ထဲ line တစ်ကြောင်း ထည့်ရုံပါပဲ။ if/elif ဆယ်ကြောင်း မလိုတော့ပါဘူး။
၂။ User ပြင်လို့ရတဲ့ error တွေအတွက် exception တစ်မျိုး
Number မဟုတ်တာ၊ operator မသိတာ၊ zero နဲ့ စားတာ၊ format မှားတာ အားလုံးက CalculatorError ကို raise လုပ်ပါတယ်။ Interface က exception တစ်မျိုးတည်းကိုပဲ ဖမ်းပြီး message ပြရုံပါပဲ။ Programming bug (ဥပမာ NameError) တွေကိုတော့ မဖမ်းလို့ ဖုံးကွယ်မသွားပါဘူး။
၃။ Input/output ကို parameter အဖြစ် ထိုးသွင်းပါ
run_session(read, write) က input() နဲ့ print() ကို တိုက်ရိုက် မခေါ်ပါဘူး။ တကယ့် program မှာ run_session(read=input, write=print) လို့ ခေါ်ပြီး test မှာတော့ ကြိုရေးထားတဲ့ line list ကို ပြန်ပေးတဲ့ function ကို ထည့်ပါတယ်။ ဒါကို dependency injection လို့ ခေါ်ပြီး loop ရဲ့ q၊ help နဲ့ error path တွေကို keyboard မလိုဘဲ စစ်နိုင်ပါတယ်။
၄။ Session command တွေက interface ရဲ့ တာဝန်ပါ
"q" နဲ့ "help" က ဂဏန်းတွက်တာ မဟုတ်ဘဲ session ကို ထိန်းတာ ဖြစ်လို့ run_session() ထဲမှာပဲ ကိုင်တွယ်ပါတယ်။ Logic က ဒီ command တွေကို မသိလို့ web version မှာ "q" အစား browser tab ပိတ်တာ၊ help အစား tooltip ပြတာမျိုး ပြောင်းလို့ ရပါတယ်။
| User ရိုက်တာ | ဘယ်အလွှာက ကိုင်လဲ | ရလဒ် |
|---|---|---|
| 15 / 4 | Logic | = 3.75 |
| 10 / 0 | Logic (CalculatorError) | Error message၊ session ဆက်သွား |
| abc * 2 | Logic (parse_number) | Error message၊ session ဆက်သွား |
| help | Interface | Operator စာရင်း ပြ |
| q | Interface | Bye! ပြပြီး loop ရပ် |
Number type ကိုလည်း သတိနဲ့ ရွေးထားပါတယ်။ float က 2.5 လို ဒသမနဲ့ -7 လို အနှုတ်ဂဏန်းကို လက်ခံပြီး ပုံမှန် calculator အတွက် လုံလောက်ပါတယ်။ Money calculator ဆိုရင် parse_number() ထဲမှာ float အစား Decimal ကို ပြောင်းသုံးရုံပါပဲ။ ကျန်တဲ့ code ကို မထိရပါဘူး။
- Interface က line တစ်ကြောင်း ဖတ်
- Logic က parse လုပ်ပြီး allowlist စစ်
- ရလဒ် ဒါမှမဟုတ် CalculatorError
- Interface က ပြပြီး နောက် line
Logic function တွေထဲမှာ input() ဒါမှမဟုတ် print() တွေ့ရင် အလွှာနှစ်ခု ရောနေပြီဆိုတဲ့ လက္ခဏာပါ။
အခြေခံ ပုံစံ
HANDLERS = {"symbol": function_for_symbol}
class AppError(Exception): ...
def evaluate(text: str) -> Result: # pure: raise AppError on bad text
...
def run(read, write) -> None: # interface: loop until quit
while (line := read("> ")) != "q":
try:
write(format_result(evaluate(line)))
except AppError as error:
write(f"Error: {error}")Dispatch table၊ custom exception၊ pure evaluate() နဲ့ read/write ကို လက်ခံတဲ့ loop ဆိုတဲ့ အစိတ်အပိုင်း လေးခုက CLI tool အများစုမှာ ပြန်သုံးလို့ရတဲ့ ပုံစံပါ။
ဥပမာ: calculator အပြည့်အစုံနဲ့ scripted session
ဒီ code က add/subtract/multiply/divide လုပ်ဆောင်ချက်တွေကို အလွှာနှစ်ခုအဖြစ် စီထားပါတယ်။ Demo အပိုင်းမှာ keyboard အစား scripted() က line တွေကို တစ်ကြောင်းချင်း ပြန်ပေးပြီး terminal မှာ မြင်ရမယ့်အတိုင်း echo လုပ်ပါတယ်။ ဒါကြောင့် code ကို ဘယ်နှစ်ခါ run run ရလဒ်တူပါတယ်။ တကယ်သုံးတဲ့အခါ နောက်ဆုံး comment အတိုင်း read=input ကို ပေးပါ။
import operator
# ===== 1. Pure logic: no input(), no print() =====
OPERATIONS = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
}
class CalculatorError(Exception):
"""A problem the user can fix by typing something else."""
def parse_number(text: str) -> float:
try:
return float(text)
except ValueError:
raise CalculatorError(f"'{text}' is not a number") from None
def calculate(a: float, op: str, b: float) -> float:
if op not in OPERATIONS:
raise CalculatorError(f"unknown operator '{op}'")
if op == "/" and b == 0:
raise CalculatorError("cannot divide by zero")
return OPERATIONS[op](a, b)
def evaluate_line(line: str) -> str:
parts = line.split()
if len(parts) != 3:
raise CalculatorError("type: number operator number, e.g. 6 * 7")
a, op, b = parts
return f"{calculate(parse_number(a), op, parse_number(b)):g}"
# ===== 2. Interface: talks to the user through read/write =====
def run_session(read, write) -> None:
write("Calculator ready. Type 'help' or 'q'.")
while True:
line = read("> ").strip()
if line in ("q", "quit"):
write("Bye!")
return
if line == "help":
write("Operators: " + " ".join(OPERATIONS) + " Example: 6 * 7")
continue
try:
write(f"= {evaluate_line(line)}")
except CalculatorError as error:
write(f"Error: {error}")
# ===== 3. Demo: a scripted user instead of the keyboard =====
def scripted(lines):
remaining = iter(lines)
def read(prompt: str) -> str:
line = next(remaining)
print(prompt + line) # echo, as a terminal would show it
return line
return read
demo = ["5 + 3", "15 / 4", "10 / 0", "2 ^ 3", "abc * 2", "7 -", "help", "q"]
run_session(read=scripted(demo), write=print)
# Real program: run_session(read=input, write=print)Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Allowlist dispatch
return OPERATIONS[op](a, b)Dict ထဲက function ကို ရှာပြီး ချက်ချင်း ခေါ်ပါတယ်။ ဒီ line မတိုင်ခင် op not in OPERATIONS ကို စစ်ထားလို့ "^" လို symbol က ဒီကို မရောက်ပါဘူး။
- Translate the low-level error
raise CalculatorError(f"'{text}' is not a number") from Nonefloat() ရဲ့ ValueError ကို user ဖတ်လို့ရတဲ့ CalculatorError အဖြစ် ပြောင်းပါတယ်။ from None က traceback ထဲမှာ မူရင်း ValueError ကို ထပ်မပြအောင် ဖုံးပါတယ်။
- Refuse before dividing
if op == "/" and b == 0:Python ရဲ့ ZeroDivisionError ကို စောင့်မနေဘဲ ကြိုစစ်ပြီး ရှင်းလင်းတဲ့ message နဲ့ raise လုပ်ပါတယ်။ Error string ကို ဘယ်တော့မှ return မလုပ်လို့ calculate() က အမြဲ float ပဲ ပြန်ပေးပါတယ်။
- Compact number formatting
return f"{calculate(parse_number(a), op, parse_number(b)):g}":g format က 8.0 ကို 8 အဖြစ်၊ 3.75 ကို 3.75 အဖြစ် ပြပါတယ်။ Significant digit ခြောက်လုံးထိ ပြလို့ 1 / 3 က 0.333333 ဖြစ်ပါတယ်။ ပိုတိကျဖို့လိုရင် format ကို ပြောင်းနိုင်ပါတယ်။
- One except for user errors
except CalculatorError as error:Logic က raise လုပ်တဲ့ error အားလုံးကို ဒီနေရာတစ်ခုတည်းမှာ ဖမ်းပြီး session ဆက်သွားပါတယ်။ ဒါကြောင့် "10 / 0" နောက်မှာလည်း calculator မပိတ်ဘဲ နောက် line ကို ဆက်မေးပါတယ်။
- Injected I/O
run_session(read=scripted(demo), write=print)Demo line list ကို keyboard အဖြစ် ထိုးသွင်းပါတယ်။ write=print ကို list.append နဲ့ အစားထိုးရင် output ကိုလည်း test ထဲမှာ list အဖြစ် စစ်လို့ရပါတယ်။
Calculator ready. Type 'help' or 'q'.
> 5 + 3
= 8
> 15 / 4
= 3.75
> 10 / 0
Error: cannot divide by zero
> 2 ^ 3
Error: unknown operator '^'
> abc * 2
Error: 'abc' is not a number
> 7 -
Error: type: number operator number, e.g. 6 * 7
> help
Operators: + - * / Example: 6 * 7
> q
Bye!Logic ကို table test နဲ့ စစ်ပါ
Logic အလွှာက pure ဖြစ်လို့ input နဲ့ မျှော်လင့်ထားတဲ့ ရလဒ်ကို table အဖြစ် ရေးပြီး loop နဲ့ စစ်လို့ရပါတယ်။ Pytest သုံးရင် @pytest.mark.parametrize နဲ့ case တစ်ခုစီကို test သီးသန့်အဖြစ် ပြပေးပါတယ်။ ဒီ table ထဲမှာ ပုံမှန် case တွေ၊ အနှုတ်ဂဏန်း၊ ဒသမ၊ zero နဲ့ စားတာ၊ format မှားတာ စတာတွေ ပါရပါမယ်။
Interface အလွှာအတွက်တော့ scripted reader နဲ့ session တစ်ခုလုံးကို run ပြီး write ထုတ်တဲ့ line တွေကို စစ်ပါ။ Test နှစ်မျိုးလုံး keyboard မလိုလို့ CI pipeline ထဲမှာ အလိုအလျောက် run လို့ရပါတယ်။
import operator
OPS = {"+": operator.add, "-": operator.sub, "*": operator.mul}
cases = [((2, "+", 3), 5), ((-4, "-", 6), -10), ((2.5, "*", 4), 10.0)]
for (a, op, b), expected in cases:
actual = OPS[op](a, b)
status = "ok" if actual == expected else "FAIL"
print(f"{status}: {a} {op} {b} = {actual}")လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Calculator က သေးငယ်ပေမဲ့ ဒီ project ရဲ့ ပုံစံက CLI tool တွေ၊ chatbot command handler တွေ၊ spreadsheet formula engine တွေနဲ့ pricing rule engine တွေမှာ တူတူပါပဲ။ Command ကို parse လုပ်၊ allowlist နဲ့ dispatch လုပ်၊ domain error တွေကို exception တစ်မျိုးနဲ့ ပြန်ပို့ပြီး interface က ဘယ်လိုပြမလဲ ဆုံးဖြတ်ပါတယ်။ Logic ကို ခွဲထားလို့ CLI version ကို Tkinter GUI ဒါမှမဟုတ် Flask API အဖြစ် ပြောင်းတဲ့အခါ evaluate_line() ကို မပြင်ဘဲ ပြန်သုံးနိုင်ပါတယ်။
User က "(2 + 3) * 4" လို အပြည့်အစုံ expression တွေ ရိုက်ခွင့်ပေးချင်ရင်လည်း eval() ကို မသုံးပါနဲ့။ Python ရဲ့ ast module နဲ့ expression ကို parse လုပ်ပြီး ခွင့်ပြုထားတဲ့ node type (number၊ BinOp) တွေကိုပဲ တွက်တဲ့ evaluator ကို ရေးတာ ဒါမှမဟုတ် စမ်းသပ်ပြီးသား parser library ကို သုံးတာက စံနည်းပါ။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Error ကို string အဖြစ် return လုပ်တာ
divide() က "Error!" string ကို ပြန်ပေးရင် caller တိုင်းက isinstance(result, str) လို စစ်ရပါမယ်။ တစ်နေရာမှာ မေ့သွားရင် string နဲ့ number ကို ပေါင်းပြီး TypeError ဖြစ်တာ ဒါမှမဟုတ် "Error!" ကို database ထဲ သိမ်းမိတာ ဖြစ်ပါတယ်။ Error ဆိုရင် exception ကို raise လုပ်ပါ။
except: ဒါမှမဟုတ် except Exception: နဲ့ အားလုံးဖမ်းတာ
Loop ထဲမှာ except Exception: print("Invalid input") လို့ ရေးရင် code ထဲက typo ကြောင့်ဖြစ်တဲ့ NameError ကိုပါ "Invalid input" လို့ ပြပြီး bug ကို ဖုံးပစ်ပါတယ်။ User ကြောင့်ဖြစ်တဲ့ error အမျိုးအစား (CalculatorError) ကိုပဲ ဖမ်းပါ။
Logic function ထဲမှာ input() ခေါ်တာ
calculate() ထဲမှာ input() ပါရင် test မှာ program က keyboard ကို စောင့်ပြီး ရပ်နေပါလိမ့်မယ်။ GUI ဒါမှမဟုတ် web version မှာလည်း ပြန်သုံးလို့ မရပါဘူး။ Value တွေကို parameter အဖြစ်ပဲ လက်ခံပါ။
Mini challenge
%၊ **၊ ans နဲ့ history ထည့်ပါ
Calculator ကို ချဲ့ပါ။ % နဲ့ ** operator ထည့်ပြီး "ans" ဆိုတဲ့ စကားလုံးက ယခင်ရလဒ်ကို ကိုယ်စားပြုရပါမယ်။ "history" command က အောင်မြင်ခဲ့တဲ့ calculation တွေကို ပြရပါမယ်။ run_lines() က line list ကို လက်ခံပြီး ပြမယ့် output line list ကို ပြန်ပေးရပါမယ်။
- ** ရဲ့ exponent က 100 ထက်ကြီးရင် CalculatorError ဖြစ်ရပါမယ် (float overflow ကို ကာကွယ်ဖို့)
- / နဲ့ % နှစ်ခုစလုံးမှာ zero နဲ့ စားရင် ငြင်းရပါမယ်
- ans ကို ပထမဆုံး calculation မတိုင်ခင် သုံးရင် ရှင်းလင်းတဲ့ error ပြရပါမယ်
- input() မသုံးရပါ၊ run_lines() က output list ကိုပဲ ပြန်ပေးရပါမယ်
import operator
class CalculatorError(Exception):
pass
def safe_power(a: float, b: float) -> float:
# TODO: refuse exponents with abs(b) > 100, otherwise return a ** b
...
OPERATIONS = {
# TODO: + - * / from the lesson, plus "%" and "**" (use safe_power)
}
def parse_operand(text: str, ans: float | None) -> float:
# TODO: "ans" -> previous answer (error if None), else float(text)
...
def evaluate(line: str, ans: float | None) -> float:
# TODO: split into 3 parts, check the operator, guard / and % by zero
...
def run_lines(lines: list[str]) -> list[str]:
"""Feed lines through the calculator and return what it would print."""
# TODO: keep ans and a history list; "history" prints past results
return []
session = ["ans + 1", "17 % 5", "ans ** 3", "2 ** 1000", "9 % 0", "ans / 4", "history"]
for shown in run_lines(session):
print(shown)ရလဒ်: ပထမ line က "no previous answer yet" error၊ ပြီးရင် = 2၊ = 8၊ exponent error၊ zero error၊ = 2 ထွက်ပြီး history က အောင်မြင်ခဲ့တဲ့ calculation သုံးခုကို ပြပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
ans နဲ့ history ကို run_lines() ထဲက local variable အဖြစ်ထားပါ။ Calculation အောင်မြင်မှပဲ ans ကို update လုပ်ပြီး history ထဲ ထည့်ပါ။ Error ဖြစ်ရင် ans က ယခင်တန်ဖိုးပဲ ကျန်ရပါမယ်။
အဖြေ ကြည့်ရန်
import operator
class CalculatorError(Exception):
pass
def safe_power(a: float, b: float) -> float:
if abs(b) > 100:
raise CalculatorError("exponent too large (limit is 100)")
return a ** b
OPERATIONS = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"%": operator.mod,
"**": safe_power,
}
def parse_operand(text: str, ans: float | None) -> float:
if text == "ans":
if ans is None:
raise CalculatorError("no previous answer yet")
return ans
try:
return float(text)
except ValueError:
raise CalculatorError(f"'{text}' is not a number") from None
def evaluate(line: str, ans: float | None) -> float:
parts = line.split()
if len(parts) != 3:
raise CalculatorError("type: number operator number")
left, op, right = parts
if op not in OPERATIONS:
raise CalculatorError(f"unknown operator '{op}'")
a, b = parse_operand(left, ans), parse_operand(right, ans)
if op in ("/", "%") and b == 0:
raise CalculatorError("cannot divide by zero")
return OPERATIONS[op](a, b)
def run_lines(lines: list[str]) -> list[str]:
"""Feed lines through the calculator and return what it would print."""
ans = None
history = []
output = []
for line in lines:
if line == "history":
output.extend(history or ["(empty)"])
continue
try:
ans = evaluate(line, ans)
history.append(f"{line} = {ans:g}")
output.append(f"= {ans:g}")
except CalculatorError as error:
output.append(f"Error: {error}")
return output
session = ["ans + 1", "17 % 5", "ans ** 3", "2 ** 1000", "9 % 0", "ans / 4", "history"]
for shown in run_lines(session):
print(shown)Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- User စာသားကို eval() နဲ့ ဘယ်တော့မှ မ run ပါနဲ့၊ operator allowlist dict ကို သုံးပါ
- Logic (parse၊ calculate) ကို pure function အဖြစ်ထားပြီး input()/print() ကို interface အလွှာမှာပဲ ထားပါ
- User ပြင်လို့ရတဲ့ error တွေကို CalculatorError လို exception တစ်မျိုးနဲ့ raise လုပ်ပါ၊ string မပြန်ပါနဲ့
- read/write ကို parameter အဖြစ်ပေးရင် interactive loop ကိုပါ keyboard မလိုဘဲ test လုပ်နိုင်ပါတယ်
The Python Tutorial — Python Software Foundation