Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

MODULE 5: Functions in Python

In Module 5, we move from writing simple scripts to building reusable blocks of code. Functions are the “verbs” of your program—they perform specific actions and help keep your code organized and DRY (Don’t Repeat Yourself).

1. Defining Functions

A function is defined using the def keyword, followed by a name and parentheses.

Example:

Python

def greet():
    print("Hello, welcome to Python!")

greet() # Calling the function

2. Parameters & Arguments

  • Parameters: The placeholders defined in the function signature.
  • Arguments: The actual values you pass into the function when calling it.

Example:

Python

def greet_user(name): # 'name' is a parameter
    print(f"Hello, {name}!")

greet_user("Alice")   # "Alice" is an argument

3. Return Statements

The return statement sends a result back to the caller. Without a return statement, a function returns None by default.

Example:

Python

def add(a, b):
    return a + b

result = add(5, 3)
print(result) # 8

4. Default & Keyword Arguments

  • Default Arguments: Values used if no argument is provided.
  • Keyword Arguments: Passing arguments by explicitly naming the parameter.

Example:

Python

def power(base, exponent=2): # exponent has a default value
    return base ** exponent

print(power(4))          # 16 (uses default 2)
print(power(exponent=3, base=2)) # 8 (keyword arguments)

5. *args and **kwargs

These allow a function to accept a variable number of arguments.

  • *args: Collects extra positional arguments as a tuple.
  • **kwargs: Collects extra keyword arguments as a dictionary.

Example:

Python

def make_pizza(size, *toppings):
    print(f"Size: {size}, Toppings: {toppings}")

make_pizza("Large", "Pepperoni", "Mushrooms", "Olives")

6. Lambda Functions

Lambdas are small, anonymous “one-liner” functions. They are often used for short-term tasks with functions like map() or filter().

Example:

Python

# square = lambda x: x * x
multiply = lambda a, b: a * b
print(multiply(5, 4)) # 20

7. Recursion

Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive function needs a base case to prevent an infinite loop.

Example (Factorial):

Python

def factorial(n):
    if n == 1: # Base case
        return 1
    else:
        return n * factorial(n - 1) # Recursive call

8. Function Documentation (Docstrings)

Docstrings are string literals that appear right after the function definition. They explain what the function does and are accessed via help() or .__doc__.

Example:

Python

def calculate_area(radius):
    """Calculates the area of a circle given its radius."""
    return 3.14 * (radius ** 2)

print(calculate_area.__doc__)

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥