
🐍 Lesson 19: Python Functions (လုပ်ဆောင်ချက်များ)
1. Function ဆိုတာဘာလဲ?
မြန်မာ → Function ဆိုတာ def keyword နဲ့ သတ်မှတ်ထားတဲ့ code block တစ်ခုဖြစ်ပြီး ခေါ်လိုက်မှသာ လုပ်ဆောင်တယ်။
English → A function is a block of code defined with the def keyword that only runs when called.
2. Function Components
- Parameters → Function ထဲကို ပို့တဲ့ input
- Return → Function ကနေ ပြန်ထွက်တဲ့ output
- Docstring → Function ရဲ့ ရှင်းလင်းချက်
3. အကျဉ်းချုပ်
✅ def function_name(parameters) → function သတ်မှတ်
✅ return → တန်ဖိုး ပြန်ပို့
✅ function_name() → function ခေါ်
✅ Parameters, return values, docstrings အသုံးပြုနိုင်
python
# ===== 1. Simple Function =====
def greet():
print("Hello, World!")
greet() # Call the function
# ===== 2. Function with Parameters =====
print(f"\n===== With Parameters =====")
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Kyaw Kyaw")
greet_person("Ma Ma")
# ===== 3. Function with Return Value =====
print(f"\n===== With Return =====")
def add(a, b):
return a + b
result = add(5, 3)
print(f"5 + 3 = {result}")
# ===== 4. Function with Default Parameters =====
print(f"\n===== Default Parameters =====")
def greet_with_title(name, title="Mr."):
print(f"Hello, {title} {name}")
greet_with_title("Aung") # Uses default "Mr."
greet_with_title("Mya", "Dr.") # Override with "Dr."
# ===== 5. Function with Multiple Return Values =====
print(f"\n===== Multiple Returns =====")
def calculate(x, y):
sum_val = x + y
diff_val = x - y
return sum_val, diff_val
s, d = calculate(10, 3)
print(f"Sum: {s}, Difference: {d}")
# ===== 6. Function with Docstring =====
print(f"\n===== With Docstring =====")
def square(n):
"""
Returns the square of a number.
Args: n (int/float)
Returns: n squared
"""
return n ** 2
print(f"Square of 5: {square(5)}")
print(f"Docstring: {square.__doc__}")
# ===== 7. Recursive Function =====
print(f"\n===== Recursive Function =====")
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(f"Factorial of 5: {factorial(5)}")You should see
Hello, World! ===== With Parameters ===== Hello, Kyaw Kyaw! Hello, Ma Ma! ===== With Return ===== 5 + 3 = 8 ===== Default Parameters ===== Hello, Mr. Aung Hello, Dr. Mya ===== Multiple Returns ===== Sum: 13, Difference: 7 ===== With Docstring ===== Square of 5: 25 Docstring: Returns the square of a number. Args: n (int/float) Returns: n squared ===== Recursive Function ===== Factorial of 5: 120