Functions

Concept of Functions

  • A block of reusable and modular code that performs a specific task
  • Helps to break down complex problems into smaller, manageable pieces
  • Improves code readability and maintainability
  • Has argument (input), code (logic), return value (output)
  • Doesn't execute until it's called/invoked
  • To invoke, we use its name followed by arguments in parentheses ()
  • Syntax:
    1. def function_name(parameters):{expression}return value

Example of a Function

    Example:
    1. def greet(name):return f"Hello, {name}!"message = greet("Rabi") print(message) # Hello, Rabi!
    2. def calculate_area(radius):pi = 3.14area = pi * radius ** 2return arearesult = calculate_area(5) print(result) # 78.5

Docstring

  • Used for documenting a function's purpose, parameters and return value
  • Added inside triple quotes """ immediately after function definition
  • Helps improve code readability and maintainability
  • AI tools can automatically generate doc strings based on code and comments
  • Can be accessed using __doc__ attribute
  • Example:
    1. def greet(name):"""Returns a greeting message."""return f"Hello, {name}!" # Hello, Alice!

Variable Scope

  • The region of code where a variable is defined and can be accessed
  • Types of Variable Scope:
    1. Global: Defined outside of a function
    2. Non-local: Defined in an enclosing function (for nested functions)
    3. Local: Defined inside a function
  • When variable is called, Python first looks in local, non-local and finally global scope.
  • If variable is not found in any of these scopes, it raises a NameError
  • We only get read access for variables in non-local and global scope.
  • To get write access, we need to use nonlocal and global keywords respectively

Variable Scope Example

  • x = 10 # Global variabledef my_function():x = 5 # Local variableprint("Inside function, x =", x)my_function() print("Outside function, x =", x) # Output: # Inside function, x = 5 # Outside function, x = 10

Default Value

  • Argument of function can be made optional by assigning default value
  • If argument is not provided during function call, default value is used
  • Default value for mutable data has to be assigned None
  • Example:
    1. def greet(name="Python"):return f"Hello, {name}!"print(greet()) # Hello, Python! print(greet("Data Engineer")) # Hello, Data Engineer!

Lambda Functions

  • One-line, Anonymous functions without name
  • Used for small, one-time operations. Often used in map, filter and reduce functions
  • Examples:
    1. square = lambda x: x ** 2 print(square(5)) # 25
    2. sum_diff = lambda x, y: (x + y, x - y) print(sum_diff(3, 4)) # (7, -1)
    3. even_chk = lambda x: 'Yes' if x % 2 == 0 else 'No' print(even_chk(4)) # Yes print(even_chk(5)) # No

Filter Function

  • Used to filter elements from a sequence based on a function that returns True/False
  • Syntax:
    1. filter(function, sequence) # Function evaluates each item and returns only those evaluated as True
    Example:
    1. numbers = [1, 2, 3, 4, 5] even_checker = lambda x: x % 2 == 0 even_numbers = list(filter(even_checker, numbers)) print(even_numbers) # [2, 4]
    2. age_list = [15, 22, 30, 17, 40] adults = list(filter(lambda x: x >= 18, age_list)) print(adults) # [22, 30, 40]

Map Function

  • Apply a function to all items of a sequence and return a new sequence with results
  • Syntax:
    1. map(function, sequence) # Function is applied to each item and a new sequence is returned
    Example:
    1. numbers = [1, 2, 3, 4, 5] square_function = lambda x: x ** 2 squared_numbers = list(map(square_function, numbers)) print(squared_numbers) # [1, 4, 9, 16, 25]
    2. num_values = ['1', '2', '3'] int_values = list(map(int, num_values)) print(int_values) # [1, 2, 3]

Reduce Function

  • Apply function recursively to the items of a sequence, reducing to a single value
  • Syntax:
    1. reduce(function, sequence) # Function is applied recursively to the items from left to right, giving a single value
    Example:
    1. from functools import reduce numbers = [1, 2, 3, 4] product = reduce(lambda x, y: x * y, numbers) print(product) # 24
    2. numbers = [1, 2, 3, 4] sum = reduce(lambda x, y: x + y, numbers) print(sum) # 10

Args

  • Used to pass a n number of non-keyword arguments to a function
  • All extra arguments are packed into a tuple in args
  • Example:
    1. def product_all(*args):total = 1for num in args:total = total * numreturn totalresult = product_all(1, 2, 3, 4) print(result) # 24

Kwargs

  • Used to pass a n number of keyword arguments to a function
  • All extra keyword arguments are packed into a dictionary in kwargs
  • Example:
    1. def print_info(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")print_info(name="Alice", age=30, city="New York") # Output: # name: Alice # age: 30 # city: New York