Efficiency and Reusability : Harnessing the Power of Functions in Python

Efficiency and Reusability : Harnessing the Power of Functions in Python

Optimizing Code with Python Functions in Building digital Solutions

In this article, we'll learn in-depth about functions in Python programming. Most applications if not all utilize built-in or customized functions to enable modularity.

Check out the previous article titled: Mastering Loop Structures in Python: Unlocking the Full Potential of Iteration in this Python series.

Function (self-contained module)

A function is a reusable, structured block of encapsulated code that is utilized to carry out a single, linked task. It is a group of program instructions packaged together as a unit to accomplish a particular task. A programming language comes with in-built functions and developers can define custom functions. Functions help for ease of reuse and code organization. The function is executed upon invocation within the program, in another function, or in another module

Functions in Python

Python has a syntax for structuring how to organize lines of code as a single unit to perform any defined operation. Custom functions can be defined with any (custom) name exception of names used for reserved keywords and built-in functions. Functions can also be referred to as subroutines, procedures, subprograms or methods in the context of OOP.

Python Programming language has two types of functions:

  1. Python Built-in functions: There are 68 built-in functions in the Python programming language.

  2. Custom (user-defined) functions

Python Built-in Functions

Several built-in functions defined by Python are automatically recognized by the interpreter. The common print() and input() functions are examples of built-in functions. Numerous functions and types that are always available are built into the Python interpreter.

#Examples of built-in functions in action
print(len("Alemsbaja Blog"))

print(type("AlemsBaja Blog"))

print("Article on Function in Python")

  • The len function is used to count the characters in the string and pass a parameter to the print function to output the count value.

  • type function is used to return the data type of the value passed as a parameter.

  • The print function is used to output a value to the console.

The list of Python built-in functions, meanings and use cases can be found here

Custom (user-defined) functions:

These are functions defined by the developer for use in the application as per the requirement or specification of the lines of code to be grouped or organized as a single unit.

Structure of a function in Python

def name_of_the_function( parameters ):
    #lines of codes to execute
    #body of the function
   return [expression] #outcome of this function
  • def keyword: the def keyword at the beginning of creating a function is like saying define a function with the name and the following.

  • name of the function: the name of the function follows after the def keyword. Function names should be concise, useful and have contextual meaning.

  • parenthesis (): the parenthesis follows suit with a colon. If the function needs external data to manipulate it can be added as a parameter in the parenthesis.

  • arguments: the values passed into the parenthesis at the invocation of the function are called arguments.

  • the body of the function: contains all the lines of code with instructions on how the function manages its responsibility and parameters when supplied.

  • the return statement: the return keyword is used to return values (single or multiple values) from the function.

Example of a custom function

#definition of the function with parameters
def caculator(value1, value2):
    print(value1 + value2)

#invocation of the function with arguments
caculator(3, 4)

Calling Function in Python

To call a function means to invoke it. Arguments will be passed into the parenthesis if the function is defined with parameters.

name_of_the_function()

#<function_name>([<arguments>])

Arguments in Python Function

Arguments are values passed into a function parenthesis when it is invoked or called.

  • Default Argument

It's the default value that a function will work with if no argument is passed when the function is invoked. The my_default_arg function below is an example of a default argument. Since no argument is passed when the function is invoked the default value gets printed. The arguments are optional when the function is invoked.

def my_default_arg(name = "Alemsbaja"):
    print(name)

my_default_arg()

#Alemsbaja
  • Keyword arguments (named arguments)

These are arguments that can be invoked with the name it was used to be defined as a parameter in the function.

def my_default_arg(name, age):
    print(name, age)

my_default_arg(age=4, name="Alemsbaja")
#Alemsbaja 4

The use of the keyword or name as an argument makes the interpreter identify the accurate parameter the value belongs to. In the example above, the value is specified to the right parameter even though the definition of the function name comes before age.

  • Positional (required) arguments in Python

These are arguments that are passed into the function in the exact or specific way they were defined as parameters in the function. The execution of the function follows the order in which the parameters were defined

def my_positional_arg(blog_name, location):
    print(location)
    print("i need to do somethings here on earth before calling the hashnode for instance")
    print(blog_name)

my_positional_arg("Earth", "Hashnode")
#these arguments are not positional or in the order it is required
#because it'll pass Earth to blog_name and Hashnode to location.

#the correct positional or required arguments format when invoking the function is
my_positional_arg("Hashnode", "Earth")

NB

It is important to know that positional or required arguments come before keyword arguments in the situation of defining a function with positional and keyword arguments.

def my_positional_def_arg(blog, location, name):
    print(location)
    print("i need to do somethings here before calling the blog for instance")
    print(blog)

my_positional_def_arg(name="Alemsbaja", "Hashnode", "Earth")

The code above will throw an error as shown below with the code editor extension

  • Arbitrary arguments (\args and \*kwargs) in Python**

  • Arbitrary positional arguments: A single asterisk symbol before a parameter when defining a function that holds non-keyword variable-length arguments denotes arbitrary positional arguments. For example:

      def arb_fxn_py(*blogs):
          for blog in blogs:
              print(blog)
          print("Number of params passed to the function:", len(blogs))
    
      arb_fxn_py("Hashnode", "Medium", "Dev.to")
    
      #output
      #Hashnode
      #Medium
      #Dev.to
      #Number of params passed to the function: 3
    

    The interpreter turns the arguments into a tuple.

    • Arbitrary keyword arguments: A double asterisk symbol before a parameter when defining a function that holds keyword variable-length arguments
def arb_fxn_py(**students):
    for stu in students.items():
        print(stu)
    print("Number of params passed to the function:", len(students))

arb_fxn_py(name = "Alemsbaja", age = 10, location = "Earth")

Higher-Order Functions in Python

Functions that take in other functions as parameters and return a function as an output are referred to as High-Order functions in Python. For example, map(), filter() - (built-in functions), and reduce() - (available functools() module)

Documentation in Python functions

The text enclosed within triple strings after the colon on the second line is referred to as the function documentation (docstring). There are single-line and multi-line Docstring. It can be used to describe the function.

  • Single-line Docstring

def my_doc_str():
    """Demonstrating docstring in Python"""
print(my_doc_str.__doc__)

  • Double-line Docstring
def my_doc_str():
    """
    Demonstrating docstring in Python
    Demonstrating multi-line docstring in Python
    One more line as an example here..........
    """
print(my_doc_str.__doc__)

The Essence of Python Functions

  1. Abstraction using the DRY principle method: Functions can be used to optimize codes.

  2. Reusability: Facilitates reuse of codes. If certain lines will be used at different sections of the program it is best to use a function to group the lines of code and invoke the function when the need arises.

  3. Functions can be used to check different parts of a program in isolation from other functionalities.

  4. Modularity: Long lines of code or complicated functionalities can be condensed into several functions.

  5. Readability: functions make code readable and inheritable.

The best way to master Python functions is to write codes and try out stuff for yourself.

Conclusion

A function is an organized, reusable block of code that is used to perform a single, related task. It is a collection of program instructions bundled together to carry out a specific function.

Python offers a syntax that can be used to arrange code lines into a single unit as a function to carry out defined operations. Python pauses when executing code after calling (invoking) a function name. It then searches for the set of instructions contained in the function until it reaches the end of the line, at which point it either returns or returns an error. A function's lines of code, or instructions, are carried out from top to bottom. The statement or result as defined is returned to the location where the function was called at the end of the code line. Functions make codes readable, inheritable and reusable.

If you're looking forward to developing applications in Python using the OOP (Object-oriented programming), the major concepts are simplified on my blog here.

Hashnode: Alemsbaja X: Alemsbaja | Youtube: Tech with Alemsbaja to stay updated on more articles

Find this helpful or resourceful?? kindly share and feel free to use the comment section for questions, answers, and contributions.

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!