
đ 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