Python Functions

As we understand the word function in layman term, it refers to an activity for a purpose. Similarly, functions in computing languages refer to a block of code which is called for a purpose. That block of code is only supposed to run when the user calls for it. In python, a user can pass data or parameters into a function and then call it. Hence, the function returns the output as the result. Functions can reuse the code hence they provide better modularity to an application in python. The user have the access to python built-in functions, however he can create his own functions as well. They are called user-defined functions. Firstly we will have a look at built-in functions in python.

Python Built-in Functions

Python has a number of built-in functions and user can use them as per his need. Listing a few of them below:
  • abs(): Returns absolute value of a number
  • any(): Returns true if all items in iterable object are True
  • ascii(): Returns the readable version of an object
  • bin(): Returns the binary value of a number
  • bytes(): Returns byes objects
  • bool(): Returns Boolean value of object
  • callable(): Returns True if specified object is callable
  • classmethod(): Converts a method to class method 
  • chr(): Returns a character value
  • complex(): Returns complex number
  • dir(): Returns list of object’s properties and methods
  • dict(): Returns the dictionary value in array form
  • divmod(): Returns the quotient and remainder for arg 1/ agr2
  • eval(): Evaluates and executes the expression
  • exec(): Executes the code
  • filter(): Used to exempt items from iterable object
  • float(): Returns floating point number
  • format():  Formats a specified value 
  • getattr(): Returns the value of specified value
  • globals(): Returns current global symbol
  • hash(): Returns hash value of the object
  • id(): Returns id of an object 
  • int(): Returns an integer value
  • list(): Returns a list
  • max(): Returns the largest item
  • next(): Returns the next iterable item
  • oct(): Converts a number into octal
  • open(): Opens a file and returns file object
  • pow(): Returns value of a to power of b
  • slice(): Returns a slice object
  • sum(): Returns sum of the items
  • tuple(): Returns a tuple
  • type(): Returns the type of an object
  • zip(): Returns single iterator from 2 or more iterators

Become a Python Certified professional by learning this HKR Python Training!

Python Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Python user-defined Functions

A user has to follow various steps to run a user defined function in python. 

1.Creating a function

  • A function is created in python using ‘def’ keyword. 
  • A block of statements will follow the name of the function and arguments containing the body of function.

Below is a basic syntax for creating a function in python:

def function():

  print("Welcome to HKR Training")

2.Calling a function

The user can call the function by calling its name having parenthesis which contains the parameters of that function. This is done once the basic structure of a code is finalized.  

Below is a python code to depict the calling of a function :

def function():

print("Welcome to HKR Training")

 function()

Output of the python code:

Welcome to HKR Training

An important thing to note while calling a function is that there cannot be more than one value for a parameter. Also, the order of arguments is very important. 

Arguments of Python Functions

Arguments in python are the values that are passed inside the function parenthesis. There is no limit to how many arguments can be. A user can have as many arguments inside a function as he wants, separating it by a comma. 

Below are 3 types of arguments that a python function can have:

Python default arguments: A python function has parameters which can further have default values. Default value will be taken up only if no argument value is passed during calling of the function
Python keyword arguments: Unlike default arguments, python also allows writing an argument in desired order if the user names the argument while calling the function. These arguments provide flexibility and good control over the values in a function
 Python arbitrary arguments: These arguments come into place when the user is not sure of how many arguments are required by a function. This generally happens while calling a function as user gets unsure of how many arguments a function will accept. So, arbitrary arguments are passed by inserting an asterisk (*) before the function parameter to state that function can now take up arbitrary number of arguments. 

Below is a python code for calling the function using keyword arguments:

def child(firstname, lastname ='Kaur', standard ='Third'):

     print(firstname, lastname, 'studies in', standard, 'Standard')

 # First keyword argument

child(firstname ='Aman')   

 # Second keyword argument             

child(firstname ='Rama', standard ='forth')

 # Third keyword argument

child(lastname ='Singh', firstname ='Babli')    

Output of the python code:

Aman Kaur studies in Third Standard

Rama Kaur studies in forth Standard

Babli Singh studies in Third Standard

Top 30 frequently asked Python Interview Questions!

Subscribe to our youtube channel to get new updates..!

Here in the above code, we can analyse that only one keyword argument is required in the first call. Then there are two arguments in the second call where one is required call and second is optional. The value will get replaced to a new passing value from the default one. We can also figure out that sequence of keyword argument is not essential in the third call. 

Understanding more about Python functions 

While working with python functions, a user might come across a lot of unwanted errors such as calling invalid functions calls. Here are some tips which can save you from the same. Let us start understanding this with a python code first:

Invalid Function Calls

def child(firstname, lastname ='Kaur', standard ='Third'):

print(firstname, lastname, 'studies in', standard, 'Standard')

 # Missing required argument here

child()                         

 # non keyword argument after a keyword argument         

child(firstname ='Rama', 'forth')

 # unknown keyword argument

child(subject ='English')

Output of the above python code:

File "", line 8

SyntaxError: positional argument follows keyword argument

This python code clearly throws up an error. Here are the reasons:

  • Value is absent for the firstname of the parameter which is an essential parameter in the first call.
  • There is clearly an argument which is non keyword followed by the keyword argument in the second call.
  • The keyword argument passed doesn’t match at all with the defined keyword argument names in the third call. 

The correct python code is shown as code 2 where all the arguments and values are passed correctly. 

Function Docstring 

The immediate next string after a function is called as document string or can also be called as Docstring. The main purpose of docstring us to state the functionality of the function. However, it is not mandatory to always use a docstring. 

Below is a basic syntax for printing a docstring to a function:

print(function_name.__doc__)

Return Statement of Function

Return statement is used to take an exit from a function and directly move back to the caller of the function. It returns the specified value to the caller. The return statement can only have a variable, a constant or an expression otherwise nothing is returned with the return statement. The syntax for the same is stated given below:

return [item_list]

If you want to Explore more about Python? then read our updated article - Python Tutorial.

Python Training Certification

Weekday / Weekend Batches

 Some more facts about python functions:

  • Python allows function recursion that means a defined function is allowed to call itself. 
  • Function definitions can never be empty.
  • A function defined inside a function in python is called nested function.

Related Articles

1.Alteryx VS Python

2.Golang Vs Python

3.Power BI With Python

Find our upcoming Python Training Certification Online Classes

  • Batch starts on 7th Jun 2023, Weekday batch

  • Batch starts on 11th Jun 2023, Weekend batch

  • Batch starts on 15th Jun 2023, Weekday batch

Global Promotional Image
 

Categories

Request for more information

Gayathri
Gayathri
Research Analyst
As a senior Technical Content Writer for HKR Trainings, Gayathri has a good comprehension of the present technical innovations, which incorporates perspectives like Business Intelligence and Analytics. She conveys advanced technical ideas precisely and vividly, as conceivable to the target group, guaranteeing that the content is available to clients. She writes qualitative content in the field of Data Warehousing & ETL, Big Data Analytics, and ERP Tools. Connect me on LinkedIn.