Lesson 7: Functions in Python

๐ŸŽฏ 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

  1. Write a function to find the factorial of a number.
  2. Create a function that checks whether a number is even or odd.
  3. Build a function to count vowels in a string.
  4. Write a function to convert Celsius to Fahrenheit.
  5. Make a calculator using functions for each operation.
  6. Use a lambda function to find the square and cube of a number.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *