How to write user defined functions in Python?

How to write user defined functions in Python?

Author: Kaushik Pal
Email: kaushikkpal@gmail.com

Overview

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.

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.

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

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.

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.

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.  

Naveen Kumar

Head of Marketing at JDM Web Technologies

6 å¹´

Hi Kaushik, I sent many emails on your email id: techalpineit@gmail.com but you did not reply, you used my content which my one of team member sent for guest posting and promotion for my comany. Here is the link https://techalpine.com/difference-between-a-custom-and-theme-based-website/ You used it for yourself and did not mention our company link, Kindly remove my content from your website.

赞
回复
Kaushik Pal

Founder & CEO at TechAlpine - (Entrepreneur/Mentor/Interviewer/Consultant/Trainer/Technical writer) -

8 å¹´

Thanks Ric. Just share it with bigger audience

赞
回复
Ricardo Arrigoni

SEO Team Lead at billiger-mietwagen.de

8 å¹´

Great article Kauhsik! Well done!

赞
回复

要查看或添加评论,请登录

Kaushik Pal的更多文章

  • Metaverse - Another Virtual Universe

    Metaverse - Another Virtual Universe

    Overview - Have you ever been to a 3D movie? Before entering the hall, you’re given special eyewear that enhances your…

  • How Kotlin can help Java and Android developers?

    How Kotlin can help Java and Android developers?

    Author: Kaushik Pal Kotlin is a high-performance; static language developed by JetBrains, the company behind the famous…

    1 条评论
  • What is Apache MapReduce2 or YARN?

    What is Apache MapReduce2 or YARN?

    Overview: Since hadoop version 0.23, MapReduce has changed significantly.

    1 条评论
  • Architecture of Oracle Application Development Framework- A brief guide

    Architecture of Oracle Application Development Framework- A brief guide

    Author: Kaushik Pal Overview: In modern application development, framework plays an important role. Without support of…

    1 条评论
  • How to integrate Facebook and Twitter with java application?

    How to integrate Facebook and Twitter with java application?

    Author: Kaushik Pal Email: kaushikkpal@gmail.com Overview: Social media revolution is become a significant event in…

    1 条评论
  • How do you differentiate virtualization from cloud computing?

    How do you differentiate virtualization from cloud computing?

    Author: Kaushik Pal Overview: People are often getting confused about the term 'cloud computing' and 'virtualization'…

    1 条评论
  • MapReduce design patterns – A brief introduction

    MapReduce design patterns – A brief introduction

    Author: Kaushik Pal Overview: Design pattern is now a common term used in almost all fields of software development…

    1 条评论
  • Apache Mahout and machine learning

    Apache Mahout and machine learning

    Author: Kaushik Pal Overview: With so many development frameworks around, it becomes important that we should be able…

    1 条评论
  • Big data protection - Steps and tools

    Big data protection - Steps and tools

    Author: Kaushik Pal Overview: Big data means huge volume of data which counts in terms of terabytes and above. These…

    1 条评论
  • What is HDFS federation?

    What is HDFS federation?

    Author: Kaushik Pal Website: www.techalpine.

    1 条评论

其他会员也浏览了