
đ Lesson 60: Python Functions (Defining & Calling Functions in Depth)
1. What is a Function?
In short â A function is a code block you group together so you can call the same task over and over.
In other words â A function is a reusable block of code that performs a specific task.
2. Why Use Functions?
- Makes your code reusable
- Keeps your code clean and modular
- Makes maintenance easier
3. Summary
â Function = reusable code block
â Parameters â input values
â Return values â output results
â Default parameters, keyword arguments supported
python
# ===== 1. Basic Function =====
def greet():
print("Hello, welcome to Python!")
greet()
# ===== 2. Function with Parameters =====
print(f"\n===== With Parameters =====")
def greet(name):
print(f"Hello, {name}")
greet("Sai")
greet("Aye")
# ===== 3. Function with Return Value =====
print(f"\n===== With Return =====")
def add(a, b):
return a + b
result = add(5, 7)
print(f"Sum: {result}")
# ===== 4. Default Parameters =====
print(f"\n===== Default Parameters =====")
def greet(name="Guest"):
print(f"Hello, {name}")
greet() # Hello, Guest
greet("Aye") # Hello, Aye
# ===== 5. Keyword Arguments =====
print(f"\n===== Keyword Arguments =====")
def introduce(name, age):
print(f"My name is {name}, I am {age} years old.")
introduce(age=25, name="Sai")
# ===== 6. Multiple Return Values =====
print(f"\n===== Multiple Returns =====")
def calculate(a, b):
return a + b, a * b, a - b
sum_val, product, diff = calculate(10, 5)
print(f"Sum: {sum_val}, Product: {product}, Diff: {diff}")
# ===== 7. Variable Arguments =====
print(f"\n===== Variable Arguments =====")
def sum_all(*args):
return sum(args)
print(f"Sum: {sum_all(1, 2, 3, 4, 5)}")
# ===== 8. Keyword Arguments (kwargs) =====
print(f"\n===== Keyword Arguments =====")
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Sai", age=25, city="Yangon")You should see
Hello, welcome to Python! ===== With Parameters ===== Hello, Sai Hello, Aye ===== With Return ===== Sum: 12 ===== Default Parameters ===== Hello, Guest Hello, Aye ===== Keyword Arguments ===== My name is Sai, I am 25 years old. ===== Multiple Returns ===== Sum: 15, Product: 50, Diff: 5 ===== Variable Arguments ===== Sum: 15 ===== Keyword Arguments ===== name: Sai age: 25 city: Yangon