
🐍 Lesson 19: Python Functions
1. What is a function?
In short → A function is a block of code defined with the def keyword, and it only runs when you call it.
More formally → A function is a block of code defined with the def keyword that only runs when called.
2. Function Components
- Parameters → the input you pass into a function
- Return → the output a function sends back
- Docstring → a description of what the function does
3. Summary
✅ def function_name(parameters) → defines a function
✅ return → sends a value back
✅ function_name() → calls the function
✅ You can use parameters, return values, and 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