TechAlpine – The Technology world

How to write user defined functions in Python?

Functions are common to all programming languages. A function can be defined as a block of re-usable code to perform specific tasks. In Python, functions are of two types, one is ‘built-in’ and the other one is ‘user-defined‘. As we know, built-in functions are usually a part of Python packages and libraries, whereas user-defined functions are written by the developers to meet certain requirements. In Python, all functions are treated as objects, so it is more flexible compared to other high-level languages.

In this article, we will focus on the user-defined functions in Python and how they can be implemented by writing code examples. The code example is very important because we feel without getting your hands dirty, learning is incomplete.

Let’s have a look at some more important sections before jumping into coding.

Importance of user-defined functions

In general, user defined functions can be written by the developers or it can be borrowed as a third party library. So, our user defined functions can also be a third party library for other users. Whatever be the scenario, user defined functions have certain advantages. Let us have a look at the following points.

  • User defined functions are reusable code blocks which are written once and used multiple times, even those can be used by other applications also.
  • These functions are very useful for writing specific business logic and common utilities. And, these functions can also be modified as per requirement.
  • It supports modular design approach. So the code is always well organized, easy to maintain and developer’s friendly.
  • As the user defined functions can be written independently, the tasks of a project can be distributed for rapid application development.
  • A well-defined and thoughtfully written user defined function can ease the application development process many fold.

Now, we have a basic understanding of the advantages. Let us have a look at different function arguments in Python.

Function arguments – Python

In Python, user defined functions can take four different types of arguments. The argument types and their meanings are pre-defined. So, a developer cannot change that, but he/she can follow these pre-defined rules to make his/her own custom functions. Following are the four types of arguments and their rules.

Default arguments:

Python has a different way of representing default values for function arguments and the syntax is also different. Default values are set to indicate that the function argument will take that value if no argument value is passed during function call. The default value is assigned by using assignment (=) operator. Following is a typical syntax for default argument. Here ‘msg’ parameter has a default value “Hello!”.

  • Function definition

def defaultArg( name, msg = “Hello!”):

  • Function call

defaultArg( name)

Required arguments:

Required arguments are the mandatory arguments of a function. These argument values must be passed in correct number and order during function call. Following is a typical syntax for required argument function.

  • Function definition

def requiredArg (str,num):

  • Function call

requiredArg (“Hello”,12)

Keyword arguments:

Keyword arguments are relevant for python function calls. The keywords are mentioned during function call along with their corresponding values. These keywords are mapped with the function arguments. So the function can easily identify corresponding values even if the order is not maintained during the function call. Following is the syntax for keyword arguments.

  • Function definition

def keywordArg( name, role ):

  • Function call

keywordArg( name = “Tom”, role = “Manager”)

OR

keywordArg( role = “Manager”, name = “Tom”)

Variable number of arguments:

This is very useful when we do not know the exact number of arguments to be passed to a function. Or we have a design where any number of arguments can be passed as per the requirement. Following is the syntax for this type of function call.

  • Function definition

def varlengthArgs(*varargs):

  • Function call

varlengthArgs(30,40,50,60)

Now, we have a fare idea about different argument types in Python. Let’s check the steps to write a user defined function.

Guidelines to write user defined functions in Python?

In this section, we will check the steps to write user defined functions in Python. These are the basic steps and for additional functionalities, we need to incorporate some more steps as per requirement.

  • Step1, declare the function with the keyword ‘def’ followed by the function name.
  • Step2, write the arguments inside the opening and closing parentheses of the function. And end the declaration by a colon.
  • Step3, add the program statements to be executed.
  • Step4, End the function with/without return statement.

Following is a typical syntax for defining user defined functions.

def userDefFunction (arg1, arg2, arg3 …):

    program statement1

    program statement3

    program statement3

    ….

   return;

Let’s try some coding examples

In this section we will cover four different examples for all the four types of function arguments.

Default arguments example

Following code snippet represents default argument example. We have written the code in a script file named defArg.py

Listing 1: Default argument example

def defArgFunc( empname, emprole = “Manager” ):  

   print (“Emp Name: “, empname)

   print (“Emp Role “, emprole)

   return;

print(“Using default value”)

defArgFunc(empname=”Nick”)

print(“************************”)

print(“Overwriting default value”)

defArgFunc(empname=”Tom”,emprole = “CEO”)

Now run the script file as shown below. It will display the following output.

User defined function

User defined function

Required arguments example

Following code snippet represents default argument example. We have written the code in a script file named reqArg.py

Listing 2: Required argument example

def reqArgFunc( empname):  

   print (“Emp Name: “, empname)

   return;  

print(“Not passing required arg value”)

reqArgFunc()

print(“Now passing required arg value”)

reqArgFunc(“Hello”)

Now, first run the code without passing required argument and the following output will be displayed.

User defined function

User defined function

Now comment out reqArgFunc() function call in the script , and run the code with required argument. The following output will be displayed.

User defined function

User defined function

Keyword arguments example

Following code snippet represents keyword argument example. We have written the code in a script file named keyArg.py

Listing 3: Keyword argument example

def keyArgFunc(empname, emprole):  

   print (“Emp Name: “, empname)

   print (“Emp Role: “, emprole)

   return;  

print(“Calling in proper sequence”)

keyArgFunc(empname = “Nick”,emprole = “Manager” )

print(“Calling in opposite sequence”)

keyArgFunc(emprole = “Manager”,empname = “Nick”)

Now run the script file as shown below. It will display the following output.

User defined function

User defined function

Variable number of arguments example

Following code snippet represents variable length argument example. We have written the code in a script file named varArg.py

Listing 4: Variable length argument example

def varLenArgFunc(*varvallist ):  

   print (“The Output is: “)

   for varval in varvallist:

      print (varval)

   return;  

print(“Calling with single value”)

varLenArgFunc(55)

print(“Calling with multiple values”)

varLenArgFunc(50,60,70,80)

Once you run the code following output will be displayed.

User defined function

User defined function

Conclusion

In this article, we have discussed different aspects of user defined functions in Python. It really has some amazing features which are very helpful for application development. Python provides different types of function arguments which cover most of the programming requirements. We have also explored how a user defined function can be written in simple steps. At the end, we have worked on some coding examples to get real experience.

Tagged on:

Leave a Reply

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


9 + 3 =

TechAlpine Books
-----------------------------------------------------------