အခန်း 15 · animation 3 ခု

Chapter 14: Function များ (Functions)

808 Coder မှ တင်ဆက်သည်

အရင်အခန်းတွေတုန်းက program တစ်ခု အစအဆုံး တစ်ဆက်တည်း ရေးလာခဲ့တယ်။ Code တွေ ရှည်လာတဲ့အခါ တူညီတဲ့အလုပ်ကို နေရာတိုင်းမှာ ထပ်ခါထပ်ခါ ရေးနေရတာကို သတိထားမိမှာပါ။ ဥပမာ — စာရင်းတွက်တိုင်း total = price * quantity လို့ ထပ်ရေးနေရတာမျိုး။ ဒီအခန်းမှာတော့ အဲဒီပြဿနာကို ဖြေရှင်းပေးမယ့် function အကြောင်း လေ့လာမယ်။ Function ဆိုတာ ကိုယ့် program ကို အပိုင်းလေးတွေ ခွဲပြီး သပ်သပ်ရပ်ရပ် စီမံခန့်ခွဲနိုင်တဲ့ အစွမ်းထက်တဲ့ လက်နက်တစ်ခု ဖြစ်တယ်။

ဒီအခန်းပြီးရင်...

  • Function ဆိုတာ ဘာလဲ၊ ဘာကြောင့် သုံးရတာလဲ ဆိုတာ ရှင်းပြနိုင်မယ်
  • def နဲ့ ကိုယ့် function ကိုယ်ရေး၊ ခေါ်သုံး၊ parameter ပေး၊ return နဲ့ ရလဒ် ပြန်ယူနိုင်မယ်
  • Default parameter၊ keyword argument၊ *args၊ **kwargs တို့ကို ယုံကြည်မှုရှိရှိ သုံးနိုင်မယ်
  • Local scope နဲ့ global scope ကွာခြားချက်ကို နားလည်ပြီး recursion ကို ရေးနိုင်မယ်
  • Function တွေနဲ့ calculator နဲ့ number guessing game လို program အသေးလေးတွေ တည်ဆောက်နိုင်မယ်

Function ဆိုတာ ဘာလဲ

Function ဆိုတာ အလုပ်တစ်ခုခုကို လုပ်ပေးတဲ့ reusable code အတုံးလေး ဖြစ်တယ်။ တစ်ခါတည်း ရေးထားပြီး လိုအပ်တိုင်း ပြန်ပြန်ခေါ်သုံးလို့ရတယ်။ မြန်မာ့ အစားအစာဆိုင်က "မုန့်လုပ်နည်း စာရွက်" နဲ့ တူတယ် — နည်းစာရွက်တစ်ရွက် ရေးထားရင် ဟင်းတစ်ခါချက်တိုင်း အစအဆုံး ပြန်စဉ်းစားစရာ မလိုဘဲ စာရွက်ကို ကြည့်ပြီး လုပ်ရုံပဲ။

Function သုံးရတဲ့ အကြောင်းရင်း ၃ ချက် ရှိတယ်။

၁။ Reusability (ပြန်လည်သုံးနိုင်ခြင်း) — တစ်ခါရေးထားတဲ့ code ကို program ထဲမှာ အကြိမ်ကြိမ် ပြန်ခေါ်သုံးနိုင်တယ်။

၂။ Modularity (အပိုင်းလိုက် ခွဲခြားနိုင်ခြင်း) — Program ကြီးတစ်ခုကို အလုပ်သေးသေးလေးတွေ ခွဲထားတော့ ဖတ်ရတာ လွယ်တယ်၊ တစ်ခုခု မှားရင် ရှာရတာ လွယ်တယ်။

၃။ Avoiding repetition (ထပ်ခါရေးခြင်းကို ရှောင်ခြင်း) — တူညီတဲ့ code ကို ထပ်ထပ်ရေးစရာ မလိုတော့ဘူး။ Programmer တွေကြားမှာ နာမည်ကြီးတဲ့ စကားရှိတယ် — DRY: Don't Repeat Yourself (ကိုယ့်ကိုယ်ကို ထပ်မရေးနဲ့)။

ဥပမာ ကြည့်ရအောင်။ Function မသုံးရင် ဒီလို ထပ်ရေးရမယ် —

print("Hello, May! Nice to meet you.")
print("Hello, Ko Aung! Nice to meet you.")
print("Hello, Thiri! Nice to meet you.")

Function သုံးရင်တော့ တစ်ခါရေးပြီး သုံးခါခေါ်ရုံပဲ (အသေးစိတ်ကို နည်းနည်း ကြာမှ လေ့လာမယ်) —

def say_hello(name):
    print(f"Hello, {name}! Nice to meet you.")

say_hello("May")
say_hello("Ko Aung")
say_hello("Thiri")

မှတ်ချက်: Program ကြီးလာလေ function နဲ့ ခွဲရေးလေ ကောင်းလေပဲ။ နောက်ပိုင်း အခန်းတွေမှာ class တွေ၊ module တွေ လေ့လာတဲ့အခါ ဒီအကျင့်က အများကြီး အထောက်အကူပြုလိမ့်မယ်။

Reference

  • W3Schools — Python Functions — Function အခြေခံ သဘောတရားကို ဥပမာတွေနဲ့ လေ့လာနိုင်တယ်
  • Python Docs — Built-in Functions — Python မှာ ပါပြီးသား function တွေရဲ့ တရားဝင် စာရင်း

Function အမျိုးအစား နှစ်မျိုး

Python မှာ function နှစ်မျိုး ရှိတယ်။

၁။ Built-in functions — Python ကိုယ်တိုင် ပေးပြီးသား function တွေ။ ဘာမှ ရေးစရာ မလိုဘူး၊ တန်းခေါ်သုံးရုံပဲ။ အရင်အခန်းတွေမှာ သုံးလာပြီးသားတွေပဲ ဖြစ်တယ် —

name = "Python"
print(len(name))          # 6
print(type(name))         # <class 'str'>
print(sum([10, 20, 30]))  # 60

age = input("Enter your age: ")
print(type(age))          # အမြဲ <class 'str'>

print()၊ len()၊ input()၊ type()၊ sum() — ဒါတွေအားလုံး built-in functions တွေပဲ။ မှတ်ထားရမှာ တစ်ခုက — ဒီ function တွေကို ကိုယ်တိုင် ရေးစရာ မလိုဘူး၊ Python interpreter က အသင့်လုပ်ပေးထားတယ် ဆိုတာပဲ။

၂။ User-defined functions — ကိုယ့်ဘာသာ def ဆိုတဲ့ keyword နဲ့ ရေးတဲ့ function တွေ။ ဒီအခန်းရဲ့ အဓိက အကြောင်းအရာပဲ ဖြစ်တယ်။

Reference

def နဲ့ ကိုယ့် Function ကိုယ်ရေးမယ်

ကိုယ့် function ကိုယ်ရေးဖို့ def keyword ကို သုံးတယ်။ Syntax က ဒီလိုပါ —

def function_name(parameter1, parameter2):
    # လုပ်ချင်တဲ့ အလုပ်
    return result

အစိတ်အပိုင်းလေးတွေ ခွဲရှင်းပြရရင် — def ဆိုတာ "ဒီကနေ function စမယ်" လို့ Python ကို ပြောတာ၊ function_name က function ရဲ့ နာမည် (snake_case နဲ့ ပေးလေ့ရှိတယ်၊ ဥပမာ calculate_total)၊ ကွင်းစကွင်းပိတ်ထဲက parameter တွေက function အထဲကို ဝင်လာမယ့် တန်ဖိုးတွေ၊ နောက်ဆုံးက colon : နဲ့ အောက်က indent လုပ်ထားတဲ့ code တွေက function ရဲ့ ကိုယ်ထည် ဖြစ်တယ်။

အရိုးရှင်းဆုံး ဥပမာနဲ့ စရအောင် —

def welcome_message():
    print("Welcome to our Python class!")

welcome_message()
print("Let's start learning.")
welcome_message()
Welcome to our Python class!
Let's start learning.
Welcome to our Python class!

အရေးကြီးတဲ့ အချက် — def နဲ့ ရေးထားရုံနဲ့ function က အလုပ်မလုပ်သေးဘူး။ welcome_message() လို့ နာမည်နောက် ကွင်းစကွင်းပိတ်နဲ့ call (ခေါ်) လုပ်မှ အထဲက code တွေ အလုပ်လုပ်တာ။ Function ကို ချက်ပြုတ်နည်းစာရွက်လို့ မြင်ရင် — စာရွက်ရေးထားရုံနဲ့ ဟင်းမကျက်ဘူး၊ စာရွက်အတိုင်း ချက်မှ ဟင်းရတာ။ Call လုပ်တာက "ချက်တော့" လို့ ပြောလိုက်တာနဲ့ တူတယ်။

Parameter နဲ့ Argument

Function ကို ပိုအစွမ်းထက်အောင် အပြင်က တန်ဖိုးတွေ ထည့်ပေးလို့ရတယ်။ Define လုပ်တဲ့အချိန် ကွင်းထဲမှာ ရေးထားတာကို parameter လို့ ခေါ်ပြီး၊ call လုပ်တဲ့အချိန် တကယ် ထည့်ပေးလိုက်တဲ့ တန်ဖိုးကို argument လို့ ခေါ်တယ်။

def say_hello(name):          # name က parameter
    print(f"Hello, {name}! Nice to meet you.")

say_hello("May")              # "May" က argument
say_hello("Ko Aung")          # "Ko Aung" က argument
Hello, May! Nice to meet you.
Hello, Ko Aung! Nice to meet you.

Parameter နှစ်ခု သုံးတဲ့ ဥပမာ —

def calculate_total(price, quantity):
    total = price * quantity
    print(f"Price: {price}, Quantity: {quantity}, Total: {total}")

calculate_total(1500, 3)
calculate_total(250, 10)
Price: 1500, Quantity: 3, Total: 4500
Price: 250, Quantity: 10, Total: 2500

Argument တွေကို ပေးတဲ့အစီအစဉ်အတိုင်း parameter တွေထဲ ဝင်သွားတယ် — 1500 က price ထဲ၊ 3 က quantity ထဲ။ ဒါကို positional argument လို့ ခေါ်တယ်။

Calling a function: arguments in, return value out caller arguments parameters function body executes return value flows back to the caller the caller continues with the value
function ခေါ်တဲ့အခါ argument ဝင်၊ return တန်ဖိုး ပြန်ထွက်ပုံ

Reference

  • W3Schools — Python Functions — def syntax နဲ့ parameter ပေးနည်းကို အဆင့်ဆင့် ရှင်းပြထားတယ်
  • Python Docs — Input/Output — ဥပမာတွေမှာ သုံးထားတဲ့ f-string နဲ့ print() အကြောင်း

return — ရလဒ် ပြန်ပို့ခြင်း

Function က အလုပ်လုပ်ပြီး ရလဒ်ကို ပြန်ပေးချင်ရင် return ကို သုံးတယ်။ ဒါက beginner တွေ အမှားများဆုံး၊ အရေးအကြီးဆုံး အချက်ပဲ — print() နဲ့ return ဟာ လုံးဝ မတူဘူး။

def add_numbers(a, b):
    result = a + b
    return result

total = add_numbers(12, 8)
print("Total:", total)
print("Double of total:", total * 2)
Total: 20
Double of total: 40

return result လို့ ရေးလိုက်တော့ 20 ဆိုတဲ့ တန်ဖိုးက function အပြင်ကို ထွက်လာပြီး total ဆိုတဲ့ variable ထဲ ရောက်သွားတယ်။ အဲဒီနောက် total ကို ကြိုက်သလို ဆက်သုံးလို့ရတယ် — နှစ်ဆ ချဲ့တာမျိုး။

print() နဲ့ ဘာကွာလဲ ဆိုတာ ဒီဥပမာမှာ ရှင်းရှင်းလင်းလင်း မြင်ရမယ် —

def just_print(a, b):
    print(a + b)

def just_return(a, b):
    return a + b

x = just_print(3, 4)   # screen မှာ 7 ပေါ်မယ်၊ ဒါပေမဲ့ x ထဲ ဘာမှမရောက်
y = just_return(3, 4)  # y ထဲကို 7 ရောက်

print("x =", x)
print("y =", y)
7
x = None
y = 7

print() က screen ပေါ်မှာသာ ပြတာ — တန်ဖိုးကို ဘယ်မှ မပို့ဘူး။ ဒါကြောင့် x ထဲ None (ဘာမှမရှိ) ပဲ ရောက်တယ်။ return ကတော့ တန်ဖိုးကို function အပြင်ထုတ် ပေးတာ။ လက်တွေ့မှာ ရလဒ်ကို ဆက်တွက်ချက်ချင်ရင် return ကို သုံးရမယ်။

မှတ်ချက်: return မပါတဲ့ function ကို call ရင် Python က အလိုအလို None ပြန်ပေးတယ်။ return နောက်မှာ ရေးထားတဲ့ code တွေက အလုပ်မလုပ်တော့ဘူး — return တွေ့တာနဲ့ function က ချက်ချင်း ရပ်ပြီး ထွက်သွားတာ။

နောက်ထပ် လက်တွေ့ ဥပမာတစ်ခု —

def celsius_to_fahrenheit(celsius):
    fahrenheit = (celsius * 9 / 5) + 32
    return fahrenheit

body = celsius_to_fahrenheit(37)
print(f"Body temperature 37C = {body}F")
Body temperature 37C = 98.6F

Reference

Default Parameter နဲ့ Keyword Argument

တခါတလေ function ကို call တိုင်း argument အကုန် ထည့်ပေးနေရတာ အလုပ်ရှုပ်တယ်။ အမြဲလိုလို တူညီတဲ့ တန်ဖိုး သုံးနေရရင် default parameter ပေးထားလို့ရတယ် —

def greet_friend(name="Friend"):
    print(f"Hello, {name}!")

greet_friend()          # argument မပေးရင် default သုံးမယ်
greet_friend("Thiri")   # ပေးရင်တော့ ပေးတဲ့ဟာ သုံးမယ်
Hello, Friend!
Hello, Thiri!

Parameter တစ်ချို့ကိုပဲ default ပေးလို့လည်း ရတယ် —

def order_drink(drink, size="medium"):
    print(f"One {size} {drink}, please!")

order_drink("coffee")          # size ကို medium အလိုလိုယူ
order_drink("tea", "large")    # ကိုယ်လိုချင်တာ ထည့်ပေး
One medium coffee, please!
One large tea, please!

သတိပြုရန်: Default value ပါတဲ့ parameter ကို နောက်ဆုံးမှာ ထားရမယ်။ def order_drink(size="medium", drink): လို့ ရေးရင် SyntaxError တက်မယ် — Python က ဘယ် argument က ဘယ် parameter လဲ ခွဲမရတော့လို့။

Keyword argument ဆိုတာက call လုပ်တဲ့အချိန် parameter နာမည်နဲ့တကွ တန်ဖိုး ပေးတာပါ —

def book_info(title, author):
    print(f"Title: {title} | Author: {author}")

book_info(author="Ma Sandar", title="Moe")
Title: Moe | Author: Ma Sandar

Argument တွေရဲ့ အစီအစဉ် မမှတ်မိလည်း နာမည်တပ်ပေးလိုက်ရင် Python က သူ့ဘာသာ မှန်တဲ့နေရာ ထည့်ပေးတယ်။ Parameter များတဲ့ function တွေမှာ အမှားကင်းပြီး ဖတ်ရတာ ပိုရှင်းတယ်။

Reference

*args နဲ့ **kwargs — အရေအတွက် အကန့်အသတ်မရှိ

တခါတလေ function ကို argument ဘယ်နှခုလာမယ် ကြိုမသိဘူး။ ဥပမာ — ဈေးဝယ်စာရင်းရဲ့ စုစုပေါင်းကို တွက်ချင်တာ၊ ပစ္စည်း ၃ မျိုးလည်း ဖြစ်နိုင်တယ်၊ ၁၀ မျိုးလည်း ဖြစ်နိုင်တယ်။ ဒီလိုအချိန်မှာ *args ကို သုံးတယ် —

def total_price(*prices):
    print("Items:", len(prices))
    print("Total:", sum(prices))

total_price(500, 1200, 800)
total_price(2500, 3500)
Items: 3
Total: 2500
Items: 2
Total: 6000

*prices ဆိုတာ ရောက်လာတဲ့ argument အားလုံးကို tuple တစ်ခုအဖြစ် စုယူလိုက်တာ။ ဘယ်နှခုလာလာ ရတယ်။

Keyword argument တွေကို အရေအတွက် အကန့်အသတ်မရှိ လက်ခံချင်ရင်တော့ **kwargs ကို သုံးတယ် —

def print_profile(**info):
    for key, value in info.items():
        print(f"{key} -> {value}")

print_profile(name="Aye", city="Yangon", age=20)
name -> Aye
city -> Yangon
age -> 20

**info က keyword argument အားလုံးကို dict တစ်ခုအဖြစ် စုယူတယ်။

နှစ်ခုလုံးကို ရောသုံးတဲ့ ဥပမာ —

def order_summary(customer, *items, **details):
    print("Customer:", customer)
    print("Items:", items)
    for key, value in details.items():
        print(f"{key}: {value}")

order_summary("Mg Mg", "rice", "curry", "water", table=5, takeaway=False)
Customer: Mg Mg
Items: ('rice', 'curry', 'water')
table: 5
takeaway: False

မှတ်ချက်: Parameter တွေရဲ့ အစီအစဉ်က အရေးကြီးတယ် — ပုံမှန် parameter အရင်၊ ပြီးမှ *args၊ နောက်ဆုံးမှ **kwargs။ * တစ်လုံးက tuple၊ * နှစ်လုံးက dict လို့ အလွယ်မှတ်ထား။

Reference

Scope — Variable ရဲ့ နယ်နိမိတ်

Scope ဆိုတာ variable တစ်ခုကို ဘယ်နေရာကနေ သုံးလို့ရလဲ ဆိုတဲ့ "နယ်နိမိတ်" ပါ။ နှစ်မျိုး ရှိတယ် —

  • Local variable — function အထဲမှာ ဖန်တီးထားတာ။ အဲဒီ function အထဲမှာပဲ သုံးလို့ရတယ်။
  • Global variable — function အပြင်မှာ ဖန်တီးထားတာ။ Program တစ်ခုလုံးက သုံးလို့ရတယ်။
score = 90  # global variable

def show_score():
    score = 10  # local variable
    print("Inside function:", score)

show_score()
print("Outside function:", score)
Inside function: 10
Outside function: 90

နာမည် score ချင်း တူနေပေမဲ့ ဒါက variable နှစ်ခု — တစ်ခုက function အထဲက local၊ နောက်တစ်ခုက အပြင်က global။ အထဲက score = 10 က အပြင်က score = 90 ကို လုံးဝ မထိဘူး။ ဒါကို shadowing (အရိပ်မိုးခြင်း) လို့ ခေါ်တယ် — အထဲက variable က အပြင်က နာမည်တူ variable ကို ခေတ္တ ဖုံးထားတာ။

နောက်တစ်ချက် — local variable ကို function အပြင်ကနေ ခေါ်သုံးလို့မရဘူး —

def make_total():
    total = 100   # local variable

make_total()
print(total)      # NameError: name 'total' is not defined

Function ပြီးသွားတာနဲ့ သူ့အထဲက local variable တွေ ပျောက်ကွယ်သွားတယ်။ ဒါက တကယ်တော့ ကောင်းတဲ့အချက်ပါ — function တစ်ခုချင်းစီက သူ့အလုပ်သူ သီးသန့်လုပ်နိုင်လို့ program ကြီးမှာ variable နာမည်တွေ ငြိစွန်းစရာ မရှိဘူး။

သတိပြုရန်: Local variable ကို function အပြင်က သုံးမိရင် NameError တက်မယ်။ Function အပြင်မှာ သုံးချင်တဲ့ တန်ဖိုးရှိရင် return နဲ့ ထုတ်ယူတာ အကောင်းဆုံး အကျင့်ပဲ။

Global variable ကို function အထဲကနေ ပြောင်းလဲချင်ရင်တော့ global keyword လိုတယ် (ခဲယဉ်းတဲ့ အခြေအနေမှာသာ သုံး) —

count = 0

def increase():
    global count
    count = count + 1

increase()
increase()
print("Count:", count)
Count: 2
Scopes: who can see which variable? global scope x = 10 function scope y = 5 local to the function can read global x X outside code cannot reach local y
global scope နဲ့ function scope ကွာခြားချက်

Reference

Recursion — သူ့ကိုယ်သူ ပြန်ခေါ်တဲ့ Function

Recursion ဆိုတာ function တစ်ခုက သူ့ကိုယ်သူ ပြန်ခေါ်တာ။ မှန်နှစ်ချပ် မျက်နှာချင်းဆိုင် ထားသလို — မှန်ထဲမှာ မှန်ပုံရိပ် အထပ်ထပ် ပေါ်နေတာနဲ့ တူတယ်။

အရင်ဆုံး loop နဲ့ ရေးတဲ့ ဗားရှင်းကို ကြည့်ရအောင်။ factorial ဆိုတာ 1 ကနေ n အထိ မြှောက်တာ — ဥပမာ 5! = 5 × 4 × 3 × 2 × 1 = 120 —

def factorial_loop(n):
    result = 1
    for i in range(1, n + 1):
        result = result * i
    return result

print(factorial_loop(5))
120

ဒါကို recursion နဲ့ ရေးရင် —

def factorial(n):
    if n == 1:          # base case — ရပ်ရမယ့် အခြေအနေ
        return 1
    return n * factorial(n - 1)

print(factorial(5))
120

ဘယ်လို အလုပ်လုပ်လဲ တစ်ဆင့်ချင်း လိုက်ကြည့်ရအောင် —

  • factorial(5) → 5 * factorial(4) (4 ရဲ့ အဖြေကို စောင့်)
  • factorial(4) → 4 * factorial(3) (3 ရဲ့ အဖြေကို စောင့်)
  • factorial(3) → 3 * factorial(2)
  • factorial(2) → 2 * factorial(1)
  • factorial(1) → 1 (base case! ဒီမှာ ရပ်ပြီ)

အဲဒီနောက် အဖြေတွေ ပြန်တက်လာတယ် — 1 → 2 → 6 → 24 → 120။ Base case ဆိုတာ recursion ရပ်ရမယ့် အခြေအနေ — ဒါမပါရင် သူ့ကိုယ်သူ အဆုံးမသတ် ပြန်ခေါ်နေပြီး Python က RecursionError နဲ့ ရပ်ပစ်လိမ့်မယ်။

သတိပြုရန်: Recursion တိုင်းမှာ base case ပါရမယ်။ မပါရင် infinite recursion ဖြစ်ပြီး program ပျက်မယ်။ စဉ်းစားရမယ့် ပုံစံက — "အသေးဆုံး ပြဿနာရဲ့ အဖြေက ဘာလဲ?" (ဒီမှာ factorial(1) = 1) ပြီးမှ "ပြဿနာကြီးကို ပြဿနာသေးနဲ့ ဘယ်လို ဖော်ပြမလဲ?" (factorial(n) = n * factorial(n-1))။

factorial(5): calls pile up, then unwind factorial(5) calls factorial(4) calls factorial(3) calls factorial(2) calls factorial(1) 120 24 6 2 1 returns unwind: 1, 2, 6, 24, 120 each call waits until the one below it returns
factorial(5) ရဲ့ recursion call stack

Reference

Function ကို Argument အဖြစ် ပေးပို့ခြင်း

Python မှာ function ဟာလည်း object တစ်ခု ဖြစ်တယ်။ ဒါကြောင့် variable ထဲ ထည့်ထားလို့ရသလို၊ နောက် function တစ်ခုထဲကို argument အဖြစ် ပို့လို့လည်း ရတယ်။

def shout(text):
    return text.upper() + "!!!"

def whisper(text):
    return "... " + text.lower() + " ..."

def deliver(style_func, message):
    print(style_func(message))

deliver(shout, "good morning")
deliver(whisper, "GOOD MORNING")
GOOD MORNING!!!
... good morning ...

deliver(shout, ...) လို့ ခေါ်တဲ့အခါ shout နောက်မှာ ကွင်းစကွင်းပိတ် မပါ တာကို သတိထား — shout() ဆိုရင် function ကို ခေါ်ပြီး ရလဒ် ယူတာ၊ shout သက်သက်ဆိုရင် function ကိုယ်တိုင်ကို ပို့တာ။ deliver အထဲရောက်မှ style_func(message) လို့ ပြန်ခေါ်တယ်။

ဒီအယူအဆက တကယ့် program တွေမှာ အများကြီး သုံးတယ် — ဥပမာ list တစ်ခုကို ကိုယ်သတ်မှတ်တဲ့ စံနှုန်းနဲ့ စီချင်ရင် sorted() ရဲ့ key မှာ function ပို့တာ၊ ခလုတ် နှိပ်ရင် ဘာလုပ်မလဲ သတ်မှတ်တဲ့ GUI program တွေမှာ callback function ပေးတာ စသဖြင့်။ ဒီအခန်းမှာ သဘောတရား သိထားရင် လုံလောက်ပြီ၊ လက်တွေ့ အသုံးချတာကို နောက်ပိုင်းမှာ ထပ်တွေ့ရမယ်။

Reference

Mini Project များ

ဒီအခန်းမှာ သင်ခဲ့တာတွေကို စုပြီး program အသေးစား နှစ်ခု တည်ဆောက်ကြည့်မယ်။ နှစ်ခုလုံးမှာ function တွေနဲ့ အလုပ်ခွဲထားတာကို သတိထား ကြည့်ပါ — ဒါပဲ modularity ရဲ့ အနှစ်သာရပါ။

Project 1: Simple Calculator

စီမံကိန်း — သင်္ချာလုပ်ငန်း ၄ ခုအတွက် function ၄ ခု၊ menu ပြတဲ့ function တစ်ခု၊ ပြီးတော့ ထပ်ခါထပ်ခါ တွက်လို့ရအောင် loop တစ်ခု။

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Error: cannot divide by zero"
    return x / y


def calculator():
    print("--- Simple Calculator ---")
    print("1. Add  2. Subtract  3. Multiply  4. Divide")

    choice = input("Choose (1/2/3/4): ")
    if choice not in ("1", "2", "3", "4"):
        print("Invalid choice!")
        return

    num1 = float(input("First number: "))
    num2 = float(input("Second number: "))

    if choice == "1":
        print("Answer:", add(num1, num2))
    elif choice == "2":
        print("Answer:", subtract(num1, num2))
    elif choice == "3":
        print("Answer:", multiply(num1, num2))
    else:
        print("Answer:", divide(num1, num2))


while True:
    calculator()
    again = input("Again? (yes/no): ")
    if again.lower() != "yes":
        print("Bye!")
        break
--- Simple Calculator ---
1. Add  2. Subtract  3. Multiply  4. Divide
Choose (1/2/3/4): 4
First number: 10
Second number: 0
Answer: Error: cannot divide by zero
Again? (yes/no): no
Bye!

မှတ်ချက်: divide() ထဲမှာ y == 0 ဟုတ်မဟုတ် စားတာကို မလုပ်ခင် အရင် စစ်ထားတယ် — ဒါကို guard clause လို့ ခေါ်တယ်။ အမှားဖြစ်နိုင်တဲ့ အခြေအနေကို ကြိုတင်စစ်ဆေးတဲ့ အကျင့်က program ကောင်းတစ်ခု ဖြစ်ဖို့ အလွန်အရေးကြီးတယ်။ ZeroDivisionError နဲ့ program ပျက်မယ့်အစား သုံးစွဲသူကို ရှင်းလင်းတဲ့ message ပြပေးနိုင်တယ်။

Project 2: Number Guessing Game

ကွန်ပျူတာက 1 ကနေ 100 အတွင်း ဂဏန်းတစ်ခု လျှို့ဝှက်ထားမယ်၊ ကစားသမားက ခန့်မှန်းရမယ်။ random module က randint() ကို သုံးမယ်။ အကြိမ် 7 ကြိမ် အခွင့်အရေး ပေးထားတယ် —

import random

def guessing_game():
    secret = random.randint(1, 100)
    tries = 0
    max_tries = 7

    print("I picked a number between 1 and 100.")
    print(f"You have {max_tries} tries!")

    while tries < max_tries:
        guess = int(input(f"Try {tries + 1}: "))
        tries = tries + 1

        if guess < secret:
            print("Too low! Go higher.")
        elif guess > secret:
            print("Too high! Go lower.")
        else:
            print(f"Correct! You got it in {tries} tries.")
            return

    print(f"Out of tries! The number was {secret}.")


guessing_game()
I picked a number between 1 and 100.
You have 7 tries!
Try 1: 50
Too high! Go lower.
Try 2: 25
Too low! Go higher.
Try 3: 42
Correct! You got it in 3 tries.

မှန်သွားတဲ့အခါ return နဲ့ function ကနေ ချက်ချင်း ထွက်သွားတယ် — loop ဆက်စရာ မလိုတော့ဘူး။ အကြိမ်ကုန်သွားရင်တော့ while loop ပြီးဆုံးပြီး အဖြေမှန် ထုတ်ပြတယ်။

မှတ်ချက်: ဒီ game မှာ guessing_game() ဆိုတဲ့ function တစ်ခုတည်းနဲ့ game logic အားလုံး ထုပ်ပိုးထားတယ်။ နောင် အခက်အခဲ အဆင့်တွေ ထပ်ထည့်ချင်ရင် (ဥပမာ အကြိမ်အရေအတွက် ရွေးခိုင်းတာ) ဒီ function ကိုပဲ ပြင်ရုံပဲ — program ရဲ့ ကျန်တဲ့ အစိတ်အပိုင်းကို ထိစရာ မလိုဘူး။ ဒါပဲ function ရဲ့ အစွမ်း။

Reference

  • W3Schools — Python Functions — Project တွေမှာ သုံးထားတဲ့ function ရေးနည်းများ
  • Python Docs — Input/Output — input() နဲ့ အသုံးပြုသူနဲ့ အပြန်အလှန် ဆက်သွယ်ပုံ

လေ့ကျင့်ခန်းများ

၁။ Fahrenheit မှ Celsius သို့ — အခန်းထဲက celsius_to_fahrenheit() ရဲ့ ပြောင်းပြန် fahrenheit_to_celsius(f) function ရေးပါ။ ဖော်မြူလာ: (f - 32) * 5 / 9။ စမ်းသပ်ချက်: fahrenheit_to_celsius(98.6) → 37.0၊ fahrenheit_to_celsius(32) → 0.0။

၂။ နာမည် ဖော်မတ် — format_name(first, last, middle="") function ရေးပါ။ middle parameter ကို default value ပေးထားရမယ်။ middle ပေးထားရင် အလယ်နာမည် ပါဝင်အောင်၊ မပေးထားရင် first နဲ့ last ပဲ ပြန်ပေးရမယ်။ စမ်းသပ်ချက်: format_name("Aung", "Min") → "Aung Min"၊ format_name("Aung", "Min", "Thura") → "Aung Thura Min"။

၃။ ပျမ်းမျှ တွက်တဲ့ function — *args သုံးပြီး average(*numbers) function ရေးပါ။ ပေးလိုက်တဲ့ ဂဏန်းအားလုံးရဲ့ ပျမ်းမျှကို return ပြန်ပေးရမယ်။ ဂဏန်း တစ်ခုမှ မပေးရင် 0 ပြန်ပေးပါ။ စမ်းသပ်ချက်: average(10, 20, 30) → 20.0၊ average(5, 15) → 10.0၊ average() → 0။

၄။ လျှပ်စစ်မီတာ ဘေလ် တွက်ချက်ခြင်း — အသုံးပြုသူ ပေးတဲ့ unit အရေအတွက်အလိုက် မီတာခ တွက်ပေးတဲ့ electricity_bill(units) function ရေးပါ။ နှုန်းထားများ: ပထမ 100 unit အခမဲ့၊ နောက် 200 unit (101–300) ကို တစ်ယူနစ် 50 ကျပ်၊ 300 အထက်ကို တစ်ယူနစ် 70 ကျပ်။ စမ်းသပ်ချက်: electricity_bill(80) → 0၊ electricity_bill(150) → 2500၊ electricity_bill(300) → 10000၊ electricity_bill(700) → 38000။ (အကြံပြု: unit အပိုင်းအလိုက် ခွဲတွက်ပြီး ပေါင်းပါ။)

၅။ Recursion နဲ့ ပေါင်းလဒ် — 1 ကနေ n အထိ ပေါင်းလဒ်ကို recursion နဲ့ တွက်တဲ့ sum_n(n) function ရေးပါ။ Base case ကို သေချာစဉ်းစားပါ။ စမ်းသပ်ချက်: sum_n(4) → 10 (1+2+3+4)၊ sum_n(10) → 55။