CodeToLive

Functions in Python

Functions in Python are reusable blocks of code that perform a specific task. They help in organizing code, avoiding repetition, and making programs modular and easier to maintain.

Defining a Function

Functions in Python are defined using the def keyword.


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

greet("Alice")
      

Returning Values

Functions can return values using the return keyword. A function can return multiple values as a tuple.


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

result = add(5, 10)
print("Sum:", result)

def get_user():
    return "Alice", 25  # Returns a tuple

name, age = get_user()
print(f"Name: {name}, Age: {age}")
      

Default Arguments

You can provide default values for function arguments. If the caller does not provide a value, the default is used.


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

greet()  # Output: Hello, Guest!
greet("Alice")  # Output: Hello, Alice!
      

Keyword Arguments

Functions can be called using keyword arguments, which allow you to specify arguments by name.


def describe_person(name, age):
    print(f"{name} is {age} years old.")

describe_person(age=25, name="Alice")
      

Lambda Functions

Lambda functions are small anonymous functions defined using the lambda keyword. They are often used for short, throwaway functions.


square = lambda x: x ** 2
print(square(5))  # Output: 25

# Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)  # Output: [1, 4, 9, 16, 25]
      

Variable-Length Arguments

Functions can accept a variable number of arguments using *args (for positional arguments) and **kwargs (for keyword arguments).


def print_args(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

print_args(1, 2, 3, name="Alice", age=25)
      

Recursion

A function can call itself, which is known as recursion. Recursion is useful for solving problems like factorial calculation.


def factorial(n):
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120
      

Scope and Lifetime of Variables

Variables defined inside a function have local scope, meaning they can only be accessed within the function. Variables defined outside functions have global scope.


x = 10  # Global variable

def my_function():
    y = 5  # Local variable
    print("Local variable y:", y)
    print("Global variable x:", x)

my_function()
# print(y)  # Error: y is not defined outside the function
      

Decorators

Decorators are used to modify the behavior of a function. They are often used for logging, timing, or access control.


def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
      
Next: Classes and Objects