Thuta Learning
Python
AdvancedProgrammingအခြေခံ

Add Two Numbers (Enhanced)

Pythonသင်ခန်းစာ 5825 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • input() က str ပြန်ပေးလို့ "10" + "20" က "1020" ဖြစ်ကြောင်း ရှင်းပြနိုင်ဖို့
  • int()၊ float()၊ Decimal() တို့ထဲက data နဲ့ကိုက်တာကို ရွေးနိုင်ဖို့
  • ValueError ကို parse လုပ်တဲ့နေရာမှာ ဖမ်းပြီး user ကို နားလည်လွယ်တဲ့ message ပြနိုင်ဖို့
  • Parse၊ calculate၊ format ကို function သီးသီးခွဲပြီး input() မပါဘဲ test လုပ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Calculator ရဲ့ ခလုတ်တွေကို နှိပ်တဲ့အခါ စက်ထဲကို ရောက်တာက ဂဏန်း မဟုတ်ပါဘူး၊ "1"၊ "0" ဆိုတဲ့ သင်္ကေတတွေပါ။ စက်က အဲဒါတွေကို ဂဏန်းအဖြစ် ပြောင်းပြီးမှ ပေါင်းပါတယ်။ Python ရဲ့ input() လည်း အတူတူပါပဲ။ User ရိုက်တာ အားလုံးကို စာသား (str) အဖြစ်ပဲ ပေးပါတယ်။

ဒါကြောင့် ဂဏန်းပေါင်းတဲ့ program မှာ အဆင့်သုံးဆင့် ရှိပါတယ်။ စာသားကို ဂဏန်းပြောင်းတာ (parse)၊ ပေါင်းတာ (add) နဲ့ ရလဒ်ကို ပြန်ပြတာ (format) ပါ။ "ten" လို ဂဏန်းမဟုတ်တဲ့ စာသား ရောက်လာရင် ဘာလုပ်မလဲဆိုတာကိုလည်း ကြိုဆုံးဖြတ်ထားရပါမယ်။

Problem → Why → Solution

ပြဿနာ: 10 + 20 = 1020

ပထမဆုံး ရေးတဲ့ "add two numbers" program က user ဆီက ဂဏန်းနှစ်လုံးကို input() နဲ့ ယူပြီး တန်းပေါင်းလိုက်ပါတယ်။ 10 နဲ့ 20 ရိုက်လိုက်တော့ 30 အစား 1020 ထွက်လာပါတယ်။ Error လည်း မတက်ပါဘူး။

int() နဲ့ ပြင်လိုက်တော့ 30 ရပါပြီ။ ဒါပေမဲ့ နောက်တစ်ယောက်က 2.5 ရိုက်လိုက်တော့ ValueError: invalid literal for int() နဲ့ program တစ်ခုလုံး ရပ်သွားပါတယ်။ try/except ထည့်ရုံနဲ့လည်း မလုံလောက်ပါဘူး။ try ထဲမှာ a, b = 50, 60 လို ပုံသေ value တွေပဲ ရှိရင် ဘာမှ error မဖြစ်နိုင်လို့ except က ဘယ်တော့မှ အလုပ်မလုပ်ပါဘူး။

add_first_try.py
a = input("First number: ")    # user types 10
b = input("Second number: ")   # user types 20
print(a + b)                   # 1020 - string concatenation

total = int(a) + int(b)        # works for 10 and 20 ...
# ... but int("2.5") or int("ten") raises ValueError and the program dies

ဘာကြောင့် ဒီလိုဖြစ်တာလဲ

+ operator က operand တွေရဲ့ type ပေါ်မူတည်ပြီး အလုပ်ပြောင်းပါတယ်။ Number နှစ်ခုဆိုရင် ပေါင်းပြီး string နှစ်ခုဆိုရင် ဆက်ပေးပါတယ်။ list နှစ်ခုဆိုရင်လည်း ဆက်ပါတယ်။ input() က အမြဲ str ပြန်ပေးလို့ conversion မလုပ်ရင် ဆက်တာပဲ ဖြစ်ပါတယ်။ int() ကလည်း "2.5" လို ဒသမပါတဲ့ စာသားကို လက်မခံဘဲ ValueError တက်ပါတယ်။

Core concept: parse၊ add၊ format ကို ခွဲပါ

"ပေါင်းတာ" ဆိုတဲ့ အလုပ်တစ်ခုတည်းမှာ တကယ်တော့ ဆုံးဖြတ်ချက် လေးခု ပါပါတယ်။ ဘယ် type တွေကို လက်ခံမလဲ၊ string ကို ဘယ်လို ပြောင်းမလဲ၊ precision ဘယ်လောက် လိုလဲ၊ input မမှန်ရင် ဘာလုပ်မလဲ။ ဒီဆုံးဖြတ်ချက်တွေကို function တစ်ခုတည်းထဲ ရောထည့်ရင် test လုပ်ရ ခက်ပါတယ်။ အဆင့်တစ်ခုစီကို သီးခြားထားပါ။

၁။ Parse: စာသားကနေ number ကို

Whole number ပဲ လက်ခံမယ်ဆိုရင် int()၊ ဒသမ လက်ခံမယ်ဆိုရင် float() ကို သုံးပါ။ နှစ်ခုစလုံးက ရှေ့နောက် space တွေကို အလိုလို ဖယ်ပေးလို့ " 12 " ကို လက်ခံပါတယ်။ float() က "nan" နဲ့ "inf" ကိုလည်း လက်ခံတာ သတိထားပါ။ Parse မအောင်မြင်ရင် ValueError တက်ပြီး အဲဒီ error ကို ဒီအဆင့်မှာပဲ ဖမ်းပါ။

၂။ Add: number တွေပဲ လက်ခံတဲ့ pure function

add_numbers(x, y) ထဲမှာ input() လည်း မရှိ၊ print() လည်း မရှိပါဘူး။ Number နှစ်ခု ဝင်ပြီး number တစ်ခု ထွက်ပါတယ်။ ဒါကြောင့် assert add_numbers(2, 3) == 5 လို test တစ်ကြောင်းနဲ့ စစ်လို့ရပြီး CLI၊ GUI၊ web API ဘယ်မှာမဆို ပြန်သုံးလို့ရပါတယ်။ Type hint တွေက editor နဲ့ type checker ကို ကူညီပေမဲ့ runtime မှာ မစစ်ပါဘူး။ add_numbers("a", "b") က "ab" ကို ပြန်ပေးပါလိမ့်မယ်။

၃။ Precision: float လား Decimal လား

float က binary floating point ဖြစ်လို့ 0.1 ကို အတိအကျ မသိမ်းနိုင်ပါဘူး။ ဒါကြောင့် 0.1 + 0.2 က 0.30000000000000004 ဖြစ်ပါတယ်။ Science နဲ့ measurement တွေမှာ ဒါက ပြဿနာမဟုတ်ပေမဲ့ ငွေကြေးမှာတော့ Decimal("0.1") ကို string ကနေ ဆောက်ပြီး သုံးပါ။ Decimal(0.1) လို float ကနေ ဆောက်ရင် float ရဲ့ အမှားပါ ပါလာပါတယ်။

၄။ Format: ရလဒ်ကို လူဖတ်လို့ရအောင်

ရလဒ်ကို ပြတဲ့အဆင့်မှာပဲ f"{total:.2f}" လို format ကို သုံးပါ။ တွက်တဲ့ function ထဲမှာ round() လုပ်လိုက်ရင် နောက်ထပ် တွက်ချက်မှုတွေမှာ အမှား စုပုံလာနိုင်ပါတယ်။

Expressionရလဒ်ဘာကြောင့်လဲ
2 + 35 (int)int နှစ်ခု ပေါင်းရင် int ရပါတယ်
2 + 3.05.0 (float)int က float အဖြစ် အလိုလို ကျယ်သွားပါတယ်
"2" + "3""23"String နှစ်ခုကို ဆက်ပါတယ်
"2" + 3TypeErrorstr နဲ့ int ကို Python က အလိုလို မပြောင်းပေးပါ
Decimal("2") + 0.5TypeErrorDecimal နဲ့ float ကို ရောမပေါင်းခွင့်ပါ
Mental model: စာသား -> number -> စာသား
  1. input() က str ပဲ ပေးတယ်
  2. Parse လုပ်ပြီး error ကို ဒီမှာ ဖမ်း
  3. Number တွေကိုပဲ ပေါင်း
  4. ပြတဲ့အခါမှ format လုပ်

Program ရဲ့ အလယ်ပိုင်းမှာ number တွေပဲ ရှိပြီး string တွေက အစွန်းနှစ်ဖက်မှာပဲ ရှိရပါမယ်။

အခြေခံ ပုံစံ

python
def parse(text: str) -> float:
    return float(text)              # raises ValueError on bad text

def add(x: float, y: float) -> float:
    return x + y                    # pure: no input(), no print()

try:
    result = add(parse(raw_a), parse(raw_b))
except ValueError:
    result = None                   # decide what bad input means

Parse က error ကို raise လုပ်ပြီး add က number တွေကိုပဲ ကိုင်ပါတယ်။ try/except ကို parse ကို ခေါ်တဲ့နေရာမှာ ထားပါ။

ဥပမာ: conversion၊ validation နဲ့ precision

Harness က keyboard ကနေ ဖတ်လို့ မရလို့ input() က ပြန်ပေးမယ့် string တွေကို typed_a နဲ့ typed_b အဖြစ် ကိုယ်တိုင်ထည့်ထားပါတယ်။ add_from_text() က parse နဲ့ error handling ကို လုပ်ပြီး add_numbers() ကတော့ number တွေကိုပဲ ပေါင်းပါတယ်။ Function နှစ်ခုလုံးကို def နဲ့ ရေးထားပါတယ်။ PEP 8 က lambda ကို နာမည်တစ်ခုထဲ assign လုပ်မယ့်အစား def ကို သုံးဖို့ အကြံပြုပါတယ်။

add_numbers.py
from decimal import Decimal

# ===== 1. Plain numbers =====
a = 5
b = 7
print(f"{a} + {b} = {a + b}")

# ===== 2. input() always returns str =====
print("\n===== Text from input() =====")
typed_a, typed_b = "10", "20"     # what input() would hand you
print(f"Without conversion: {typed_a + typed_b}")
print(f"With int():         {int(typed_a) + int(typed_b)}")


# ===== 3. Parse, then add, then format =====
def add_numbers(x: float, y: float) -> float:
    return x + y


def add_from_text(first: str, second: str) -> str:
    try:
        x, y = float(first), float(second)
    except ValueError:
        return f"Error: {first!r} or {second!r} is not a number"
    return f"{x} + {y} = {add_numbers(x, y)}"


print("\n===== Validated input =====")
print(add_from_text(" 12.5", "7.5 "))
print(add_from_text("ten", "5"))

# ===== 4. Floats versus Decimal =====
print("\n===== Precision =====")
print(f"0.1 + 0.2 = {0.1 + 0.2}")
print(f"Decimal:    {Decimal('0.1') + Decimal('0.2')}")

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Strings join, numbers addprint(f"Without conversion: {typed_a + typed_b}")

    typed_a နဲ့ typed_b က str ဖြစ်လို့ + က "10" နောက်မှာ "20" ကို ဆက်ပြီး "1020" ဖြစ်ပါတယ်။ နောက် line မှာ int() နဲ့ ပြောင်းပြီးမှ 30 ရပါတယ်။

  2. Parsing inside try x, y = float(first), float(second)

    ValueError တက်နိုင်တဲ့ conversion ကိုပဲ try ထဲမှာ ထားပါတယ်။ float() က " 12.5" လို space ပါတဲ့ စာသားကို လက်ခံပြီး "ten" ကို ငြင်းပါတယ်။

  3. Helpful error message return f"Error: {first!r} or {second!r} is not a number"

    !r က user ရိုက်ခဲ့တဲ့ စာသားကို quote နဲ့ ပြလို့ space အပို ဒါမှမဟုတ် ဗလာ string ကို မြင်နိုင်ပါတယ်။ Program က crash မဖြစ်ဘဲ message ကို ပြန်ပေးပါတယ်။

  4. Pure addition return x + y

    add_numbers() က ပေါင်းတာ တစ်ခုပဲ လုပ်ပါတယ်။ ဒီ function ကို input() မလိုဘဲ test လုပ်လို့ရပါတယ်။

  5. Exact decimal arithmeticprint(f"Decimal: {Decimal('0.1') + Decimal('0.2')}")

    Decimal ကို string ကနေ ဆောက်လို့ 0.1 က အတိအကျ ဖြစ်ပြီး ရလဒ်က 0.3 ပါ။ float version ကတော့ 0.30000000000000004 ဖြစ်ပါတယ်။

You should see
5 + 7 = 12

===== Text from input() =====
Without conversion: 1020
With int():         30

===== Validated input =====
12.5 + 7.5 = 20.0
Error: 'ten' or '5' is not a number

===== Precision =====
0.1 + 0.2 = 0.30000000000000004
Decimal:    0.3

Interactive version ကို ဘယ်လို ချိတ်မလဲ

Pure function တွေ ရပြီဆိုရင် input() ကို အပြင်ဆုံးမှာပဲ ထည့်ပါ။ User က မှန်တဲ့ ဂဏန်း ရိုက်တဲ့အထိ ပြန်မေးချင်ရင် while True loop ထဲမှာ parse လုပ်ပြီး ValueError ရရင် message ပြကာ continue လုပ်ပါ။ Parse အောင်မြင်ရင် break ပါ။

ဒီလို ခွဲထားရင် logic ကို test လုပ်တဲ့အခါ keyboard မလိုတော့ပါဘူး။ Interactive အပိုင်းကလည်း လိုင်းအနည်းငယ်ပဲ ကျန်လို့ မှားစရာ နည်းသွားပါတယ်။ အောက်က read parameter ရဲ့ default က input ဖြစ်ပေမဲ့ demo မှာ ကြိုပြင်ထားတဲ့ အဖြေတွေကို ပြန်ပေးတဲ့ function ကို ထည့်ထားလို့ retry loop ကိုတောင် test လုပ်လို့ ရပါတယ်။

ask_number.py
def ask_number(prompt: str, read=input) -> float:
    while True:
        text = read(prompt)
        try:
            return float(text)
        except ValueError:
            print(f"{text!r} is not a number, please try again.")


answers = iter(["ten", "12.5"])      # stands in for a real user
print(ask_number("First: ", read=lambda prompt: next(answers)))

bool လည်း int ပါ

Python မှာ bool က int ရဲ့ subclass ဖြစ်လို့ True + True က 2 ပါ။ Type ကို runtime မှာ စစ်တဲ့ function တွေမှာ isinstance(x, int) က True/False ကိုပါ လက်ခံတာ သတိထားပါ။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ

ဂဏန်းပေါင်းတာက shopping cart total၊ invoice၊ expense tracker၊ spreadsheet import စတဲ့ နေရာတိုင်းမှာ ပါပါတယ်။ ဒီနေရာတွေမှာ data က user form၊ CSV file ဒါမှမဟုတ် JSON API ကနေ စာသားအဖြစ် ရောက်လာလေ့ရှိပါတယ်။ "1,000.50" လို comma ပါတဲ့ စာသား၊ ဗလာ cell၊ "N/A" လို စာသားတွေ ရောနေတတ်ပါတယ်။

ငွေကြေးအတွက် team အများစုက Decimal ကို string ကနေ ဆောက်ပြီး သုံးပါတယ်။ တချို့က ပြားအရေအတွက်ကို int အဖြစ် သိမ်းပါတယ် (1999 = 19.99)။ Currency မတူတဲ့ amount နှစ်ခုကို ပေါင်းခွင့်မပြုဖို့လည်း စစ်ရပါတယ်။ Parse function ကို test case table နဲ့ စစ်ပါ: "10"၊ " 2.5 "၊ ""၊ "abc"၊ "1e3"၊ "nan" တို့အတွက် ဘာဖြစ်ရမလဲဆိုတာ ကြိုရေးထားပါ။ ဒေသအလိုက် format တွေကိုလည်း သတိထားပါ။ ဥရောပနိုင်ငံ အများစုမှာ "1.000,50" က တစ်ထောင်နဲ့ ထက်ဝက်ကို ဆိုလိုပြီး ရိုးရိုး parser က လုံးဝ မတူတဲ့ ဂဏန်းအဖြစ် ဖတ်သွားပါလိမ့်မယ်။

အမှားများ

ဖြစ်လေ့ရှိတဲ့ အမှားများ

ValueError တက်လို့ မရတဲ့ code ကို try ထဲထည့်တာ

try ထဲမှာ a, b = 50, 60 လို ပုံသေ value ပဲ ရှိရင် except ValueError က ဘယ်တော့မှ မရောက်ပါဘူး။ Error handling ရှိတယ်လို့ ထင်ရပေမဲ့ တကယ်တော့ ဘာမှ မကာကွယ်ပါဘူး။ Conversion (int()၊ float()) ကို try ထဲ ထည့်ပြီး "ten" လို input နဲ့ စမ်းကြည့်ပါ။

ဒသမ input ကို int() နဲ့ ပြောင်းတာ

int("2.5") က 2 ကို ပြန်မပေးပါဘူး၊ ValueError တက်ပါတယ်။ ဒသမ လက်ခံချင်ရင် float() ဒါမှမဟုတ် Decimal() ကို သုံးပါ။ int(float("2.5")) က 2 ဖြစ်ပေမဲ့ ဒသမကို ဖြတ်ပစ်တာ (truncate) ဖြစ်လို့ ရည်ရွယ်ချက်ရှိမှပဲ သုံးပါ။

ငွေကို float နဲ့ တွက်တာ

Item ရာနဲ့ချီတဲ့ cart total ကို float နဲ့ ပေါင်းရင် ပြားအနည်းငယ် ကွာတဲ့ ရလဒ်တွေ ထွက်လာနိုင်ပြီး accounting report နဲ့ မကိုက်တော့ပါဘူး။ Decimal("19.99") ဒါမှမဟုတ် int cents ကို သုံးပါ။

Mini challenge

Expense list ကို Decimal နဲ့ ပေါင်းပါ

Spreadsheet ကနေ ကူးလာတဲ့ amount စာသား list တစ်ခုကို ပေါင်းပါ။ parse_amount() က စာသားတစ်ခုကို Decimal ပြောင်းပြီး total_amounts() က valid amount တွေကို ပေါင်းကာ မမှန်တဲ့ entry တွေကို error list ထဲ စုပါမယ်။

  • "1,000.50" လို comma ပါတဲ့ amount နဲ့ ရှေ့နောက် space ကို လက်ခံရပါမယ်
  • ဗလာ entry တွေကို error မပြဘဲ ကျော်ရပါမယ်
  • "abc" နဲ့ "NaN" ကို error list ထဲ ထည့်ရပါမယ်
  • (total, errors) tuple ကို ပြန်ပေးရပြီး input() မသုံးရပါ
expenses.py
from decimal import Decimal, InvalidOperation


def parse_amount(text: str) -> Decimal:
    """'  12.50 ' -> Decimal('12.50'); raise ValueError for bad input."""
    # TODO: strip spaces and remove thousands separators
    # TODO: Decimal(...) raises InvalidOperation -> re-raise as ValueError
    # TODO: reject NaN and Infinity (Decimal.is_finite())
    ...


def total_amounts(entries: list[str]) -> tuple[Decimal, list[str]]:
    """Add every valid entry; skip blanks; collect bad entries."""
    # TODO: start from Decimal("0"), loop, skip blanks, collect errors
    ...


# TODO: total the list ["19.99", " 0.01", "", "1,000.50", "abc", "NaN"]
# TODO: print the total, the errors, and the result for an empty list

ရလဒ်: Total: 1020.50 ထွက်ပြီး Errors ထဲမှာ 'abc' နဲ့ 'NaN' အတွက် message နှစ်ခု ပါပါမယ်။ Empty list က (Decimal('0'), []) ကို ပြန်ပေးပါမယ်။

အရိပ်အမြွက် ကြည့်ရန်

Decimal("abc") က ValueError မဟုတ်ဘဲ decimal.InvalidOperation ကို raise လုပ်ပါတယ်။ raise ValueError(...) from None နဲ့ ပြောင်းပြီး caller က exception type တစ်မျိုးတည်းကိုပဲ ဖမ်းရအောင် လုပ်ပါ။

အဖြေ ကြည့်ရန်
expenses.py
from decimal import Decimal, InvalidOperation


def parse_amount(text: str) -> Decimal:
    """'  12.50 ' -> Decimal('12.50'); raise ValueError for bad input."""
    cleaned = text.strip().replace(",", "")
    try:
        amount = Decimal(cleaned)
    except InvalidOperation:
        raise ValueError(f"not a number: {text!r}") from None
    if not amount.is_finite():
        raise ValueError(f"not a finite amount: {text!r}")
    return amount


def total_amounts(entries: list[str]) -> tuple[Decimal, list[str]]:
    """Add every valid entry; skip blanks; collect bad entries."""
    total = Decimal("0")
    errors = []
    for entry in entries:
        if not entry.strip():
            continue
        try:
            total += parse_amount(entry)
        except ValueError as error:
            errors.append(str(error))
    return total, errors


total, errors = total_amounts(["19.99", " 0.01", "", "1,000.50", "abc", "NaN"])
print(f"Total:  {total}")
print(f"Errors: {errors}")
print(total_amounts([]))

Quick Quiz 1 / 3

a = input() မှာ user က 7 ရိုက်ပြီး b = input() မှာ 3 ရိုက်ပါတယ်။ print(a * 2 + b) က ဘာထုတ်မလဲ။

Quick Quiz 2 / 3

Shop total အတွက် 0.10 ကို ဘယ်လို သိမ်းတာ အမှန်ဆုံးလဲ။

Quick Quiz 3 / 3

ဒီ code မှာ ဘာမှားနေလဲ: try: a, b = 50, 60; total = a + b except ValueError: print("bad input")

မှတ်ထားရမယ့် အချက်များ

  • input() က အမြဲ str ပြန်ပေးလို့ ပေါင်းခင် int()/float()/Decimal() နဲ့ ပြောင်းပါ
  • + က number တွေကို ပေါင်းပြီး string နဲ့ list တွေကို ဆက်ပါတယ်
  • ValueError ကို conversion လုပ်တဲ့နေရာမှာ ဖမ်းပြီး input() ကို program ရဲ့ အပြင်ဆုံးမှာ ထားပါ
  • ငွေကြေးအတွက် string ကနေ ဆောက်တဲ့ Decimal ဒါမှမဟုတ် int cents ကို သုံးပါ

The Python Tutorial — Python Software Foundation

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Add Two Numbers (Enhanced) | Thuta Learning