0 Comments

Functions in Python are reusable blocks of code that perform specific tasks. They help to organize your code, improve readability, and promote code reusability.

Python Function Syntax

Below is the syntax for defining a Python function:


def function_name(arguments):
    """Function documentation"""
    # Function body
    return value  # Optional return statement
  • def: Keyword used to define a function.
  • function_name: The name you give to your function.
  • arguments: Optional parameters that the function can accept.
  • documentation: A docstring that explains the function’s purpose.
  • function body: The code that the function executes.
  • return value: Optional value that the function returns.

Arguments and Return Values

Arguments: Values passed to a function when it is called.
Return Values: Values that a function sends back to the caller.


def greet(name):
    print("Hello, " + name + "!")

def add(x, y):
    return x + y

greet("Alice")
result = add(5, 3)
print(result)

Global and Local Scope Variables

Global Variables: Variables defined outside of functions.
Local Variables: Variables defined inside functions.


global_var = 10

def my_function():
    local_var = 20
    print(global_var)  # Accessing global variable
    print(local_var)  # Accessing local variable

my_function()

Use of Pass Statement

The pass statement is a placeholder that does nothing. It is often used to define empty functions or placeholders for future code.


def empty_function():
    pass

Return Statement

The return statement is used to exit a function and optionally return a value.


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

range() Function

The range() function generates a sequence of numbers.


for i in range(5):
    print(i)

*args and **kwargs

*args: Collects multiple positional arguments into a tuple.
**kwargs: Collects multiple keyword arguments into a dictionary.


def my_function(*args, **kwargs):
    print(args)
    print(kwargs)

Closures

Closures are functions that capture variables from their enclosing scope.


def outer_function(x):
    def inner_function(y):
        return x * y
    return inner_function

multiply_by_2 = outer_function(2)
result = multiply_by_2(5)
print(result)

self as Default Argument

In class methods, self is implicitly passed as the first argument.


class MyClass:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print("Hello, " + self.name + "!")

Decorators

Decorators are functions that modify the behavior of other functions.


def my_decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@my_decorator
def my_function():
    print("Inside my_function")

my_function()

Map, Filter, and Reduce

  • map(): Applies a function to each element of an iterable.
  • filter(): Filters elements from an iterable based on a condition.
  • reduce(): Applies a function to an iterable and reduces it to a single value.

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
product = reduce(lambda x, y: x * y, numbers)

Lambda Functions

Lambda functions are small, anonymous functions.


double = lambda x: x * 2
print(double(5))

Leave a Reply

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

Related Posts