Python Custom Functions Explained with Examples: A Comprehensive Guide

    By: Thad Mertz
    6 months ago

    Python, known for its simplicity and flexibility, allows you to create custom functions to solve a wide range of tasks. In this blog post, we'll dive into the world of Python custom functions, exploring how to pass various data types as arguments. Understanding the different argument types is crucial for writing clean and efficient Python code. By the end of this guide, you'll have a solid grasp of how to use custom functions with different argument types.


    Function Basics


    Before we dive into the specifics of different argument types, let's start with the basics of creating a custom function in Python:



    def custom_function(arg1, arg2):
      # Function body
      result = arg1 + arg2
      return result
    



    In the above example, we have defined a simple custom function called `custom_function` that takes two arguments, `arg1` and `arg2`. It adds the two arguments together and returns the result.


    Argument Types


    1. Integer Arguments



    def add_numbers(num1, num2):
      result = num1 + num2
      return result
    
    # Example usage:
    sum_result = add_numbers(5, 7)
    print(sum_result) # Output: 12
    



    In this example, we've created a function `add_numbers` that takes two integer arguments and returns their sum.


    2. Float Arguments


    def calculate_average(num_list):
      avg = sum(num_list) / len(num_list)
      return avg
    
    # Example usage:
    average = calculate_average([3.5, 4.0, 5.5])
    print(average) # Output: 4.333333333333333
    



    Here, the `calculate_average` function accepts a list of floating-point numbers and calculates their average.


    3. String Arguments



    def greet(name):
      message = f"Hello, {name}!"
      return message
    
    # Example usage:
    greeting = greet("Alice")
    print(greeting) # Output: "Hello, Alice!"
    



    This `greet` function takes a string argument `name` and returns a greeting message.


    4. List Arguments


    def find_max(numbers):
      max_value = max(numbers)
      return max_value
    
    # Example usage:
    max_num = find_max([12, 45, 7, 28, 91])
    print(max_num) # Output: 91
    



    In this example, we define a `find_max` function that accepts a list of numbers and returns the maximum value.


    5. Dictionary Arguments



    def get_value_from_dict(dictionary, key):
      if key in dictionary:
        return dictionary[key]
      else:
        return "Key not found"
    
    # Example usage:
    student_info = {"name": "John", "age": 25, "grade": "A"}
    grade = get_value_from_dict(student_info, "grade")
    print(grade) # Output: "A"
    



    The `get_value_from_dict` function takes a dictionary and a key as arguments, returning the corresponding value from the dictionary.


    Here are some Important Argument types:


    Certainly! Here are examples of custom functions in Python that accept different argument types, including lists, dictionaries, arbitrary arguments, and sets:


    1. List as an Argument:


    def find_max(numbers):
      max_value = max(numbers)
      return max_value
    
    # Example usage:
    max_num = find_max([12, 45, 7, 28, 91])
    print(max_num) # Output: 91
    


    In this example, the `find_max` function takes a list of numbers as an argument and returns the maximum value from that list.


    2. Dictionary as an Argument:


    def get_value_from_dict(dictionary, key):
      if key in dictionary:
        return dictionary[key]
      else:
        return "Key not found"
    
    # Example usage:
    student_info = {"name": "John", "age": 25, "grade": "A"}
    grade = get_value_from_dict(student_info, "grade")
    print(grade) # Output: "A"
    


    The `get_value_from_dict` function accepts a dictionary and a key as arguments, returning the corresponding value from the dictionary.


    3. Arbitrary Arguments (using `*args`):


    def concatenate_strings(*args):
      result = ""
      for arg in args:
        result += arg
      return result
    
    # Example usage:
    concatenated = concatenate_strings("Hello", " ", "World", "!")
    print(concatenated) # Output: "Hello World!"
    


    In this case, `*args` allows the function to accept a variable number of string arguments and concatenates them into a single string.


    4. Set as an Argument:


    def unique_elements(input_set):
      return list(input_set)
    
    # Example usage:
    my_set = {1, 2, 2, 3, 4, 4, 5}
    unique_list = unique_elements(my_set)
    print(unique_list) # Output: [1, 2, 3, 4, 5]
    


    Here, the `unique_elements` function accepts a set as an argument and converts it into a list, removing duplicate elements in the process.


    These examples demonstrate how Python functions can work with different data types, providing flexibility and versatility in your code. Whether you're dealing with lists, dictionaries, arbitrary arguments, or sets, Python's ability to handle various data types makes it a powerful language for writing custom functions.