Python Functions

In Python, a function is a block of code that only runs when it is called. Functions help in breaking the program into smaller, modular, and reusable parts. Python functions can have parameters (arguments) that allow you to pass data into the function and return a value using the return statement.
Python functions are an essential part of writing clean and efficient code. They allow for code reusability, modularity, and better organization of your programs. By understanding functions, parameters, return values, and other related concepts, you can write more efficient and readable Python programs.

What is a Function?

1. Defining and Calling a Function


# Example: Defining a Function
def greet():
    print("Hello, welcome to Python Functions!")

# Calling the function
greet()

Output

Hello, welcome to Python Functions!

Functions with Parameters

Functions can accept parameters that provide additional information for processing.


def greet_user(name):
    print(f"Hello, {name}!")

greet_user("Alice")
greet_user("Bob")
            

Output

Hello, Alice! Hello, Bob!

Functions with Return Values

Functions can return values using the return statement. This allows functions to send back a result to the caller.


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

result = add_numbers(5, 7)
print("Sum:", result)
            

Output

Sum: 12

Default Arguments

Python allows function parameters to have default values, which are used if no argument is passed during the function call.


def greet(name="Guest"):
    print(f"Hello, {name}!")

greet("John")
greet()

Output

Hello, John! Hello, Guest!

Keyword Arguments

Python functions support keyword arguments, which allow you to specify the parameter names during function calls.


def display_info(name, age):
    print(f"Name: {name}, Age: {age}")

display_info(age=30, name="Alice")
            

Output

Name: Alice, Age: 30

Variable-Length Arguments

You can pass a variable number of arguments to a function using *args for non-keyword arguments and **kwargs for keyword arguments.


def sum_all(*args):
    return sum(args)

print("Sum:", sum_all(1, 2, 3, 4))
            

Output

Sum: 10

Lambda Functions

Lambda functions are small anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression.

Syntax


lambda arguments: expression
  • The expression is evaluated and returned.
  • Lambda functions are often used for short, simple tasks where defining a full function is unnecessary.
  • Examples:

    1. Basic Example

    
    # Regular function
    def add(a, b):
        return a + b
    # Lambda function
    add_lambda = lambda a, b: a + b
    print(add_lambda(3, 5)) 
                

    Output

    8

    2. Single Argument

    
    square = lambda x: x ** 2
    print(square(4))
                

    Output

    16

    3. Multiple Arguments

    
    multiply = lambda x, y: x * y
    print(multiply(3, 7))
                

    Output

    21

    When to use Lambda Functions

    Limitations