Python User Defined Functions

Python is a powerful programming language with a robust library of functions and other resources for faster development. Its inbuilt functions are a great support to any Python Programmer. Sometimes it is easier to write your own functions. If in-built functions are not sufficient to implement your logic you have to create your own functions.  For such cases you can create User Defined Functions.  This post is about how to create and call Python User Defined Functions.

Python User Defined Functions-Syntax

def Function-Name(Argument list):

                statements to define function body

[return statement]

To define a function you will always use the keyword def.  It is followed by the name of the python user defined function and the list of arguments in parenthesis. The argument list is followed by colon “:”.

You will recall that the blocks in Python are defined with the help of indentation. To define the function body statements press enter (to go to net line of code) and tab key (to define indentation of the statement)

Return statement is the last statement of function . It returns value evaluated within the function.

Example – A python user defined function to add two numbers passed as parameters.

def  addnums(x,y): # name of function and two arguments in parenthesis.
    c=x+y 	# expression to sum two numbers
    print(c)	# print the added value stored in variable c

OR

def  addnums(x,y): # name of function and two arguments in parenthesis.
    c=x+y 	# expression to sum two numbers
    return (c)	# returns the added value stored in variable c

Calling Python User Defined Functions

The created function can be called by writing the Function name and passing the required parameters. This function created can be called after the function definition in the saved Python file. Other method is to call it from Python Idle command prompt. If the program is compiled with no errors it will display the result.

Syntax

Function-name(actual parameter list)

Example – calling the function addnums

addnums(40,50)

python user defined functions-example

Note: A function created with def  keyword on the Idle Command Prompt will be available. If you close Idle or any tool to run Python commands, the function defined in this session will not be available in the next session.

So, it is always advisable to save Python files. This way you can use the python user defined functions again by importing the compiled Python files in other programs.

Be First to Comment

Leave a Reply

Your email address will not be published.