๐ฏ Lesson Objective
To understand what functions are, how to create and use them, and why they are essential for code organization and reuse.
๐ง 1. What Is a Function?
A function is a reusable block of code that performs a specific task.
Functions make programs easier to read, test, and maintain.
โ๏ธ 2. Syntax of a Function
def function_name(parameters):
# code block
return value
โ Example:
def greet():
print("Hello, welcome to Python!")
greet()
Output:
Hello, welcome to Python!
๐งฉ 3. Function with Parameters
Functions can accept inputs (called parameters) that make them flexible.
def add_numbers(a, b):
result = a + b
print("Sum:", result)
add_numbers(5, 7)
Output:
Sum: 12
๐งพ 4. Function with Return Statement
A function can return data back to the caller using the return keyword.
def multiply(a, b):
return a * b
result = multiply(4, 6)
print("Product:", result)
Output:
Product: 24
๐ 5. Default Parameters
If a parameter value isnโt provided, Python uses the default.
def greet(name="User"):
print("Hello,", name)
greet("Sameer")
greet()
Output:
Hello, Sameer
Hello, User
๐งฎ 6. Function with Multiple Returns
A function can return multiple values separated by commas.
def calculate(a, b):
return a + b, a - b
sum_val, diff_val = calculate(10, 5)
print("Sum:", sum_val)
print("Difference:", diff_val)
Output:
Sum: 15
Difference: 5
๐ 7. Variable Scope
Variables defined inside a function are local, while those outside are global.
x = 10 # Global variable
def show():
x = 5 # Local variable
print("Inside function:", x)
show()
print("Outside function:", x)
Output:
Inside function: 5
Outside function: 10
๐งฐ 8. Lambda (Anonymous) Functions
A lambda function is a short, one-line function without a name.
square = lambda x: x * x
print(square(4))
Output:
16
๐ 9. Real-Life Example: Calculator Function
def calculator(a, b, operation):
if operation == "add":
return a + b
elif operation == "subtract":
return a - b
elif operation == "multiply":
return a * b
elif operation == "divide":
return a / b
else:
return "Invalid operation"
print(calculator(10, 5, "add"))
print(calculator(10, 5, "divide"))
Output:
15
2.0
๐ง 10. Practice Ideas
- Write a function to find the factorial of a number.
- Create a function that checks whether a number is even or odd.
- Build a function to count vowels in a string.
- Write a function to convert Celsius to Fahrenheit.
- Make a calculator using functions for each operation.
- Use a lambda function to find the square and cube of a number.

Leave a Reply