User Defined Functions in Python

User Defined Functions in Python

User Defined Functions in Python

Function-

A function is a self-contained block of statement to perform a specific task.

Basically, there are two types of function

Library Functions

These functions are are provided by a Python’s package and a user only need to call it in your program.

User Defined Functions in Python

As name indicates that a user will define for its own use. User will decide number of arguments a function will receive and return, what statement a function will contain.

Python uses a “def” keyword to define a function. Function in Python is preceded by def keyword and is followed by a colon(:).

For example if you want to define a function to add two variables different types of functions are defined. Based on how many argument they receive and return.

Type-1-No Arguments and no Returns

def add(): # Definition of add() function
a=10
b=5
sum=a+b
print(sum)
add() # Calling add() function
In the above program you can see add() function is preceded by def keyword and is followed by a colon(:).
Unlike C, Python does not require type of return or type of argument.

Type-2-Two Arguments and no Returns

def add(10,5): # Definition of add() function
sum=a+b
print(sum)
add(10,5) # Calling add function

Type-3-Two Arguments and One Return

def add(10,5): # Definition of add() function
sum=a+b
return sum
s=add(10,5) # Calling add function
print(s)

Type-4 Multiple Arguments and Multiple Returns

Python can return multiple variables from a function.
def arithmeticop(a,b): #Definition of arithmeticop() function
sum=a+b
sub=a-b
mul=a * b
div=a/b
return sum, sub, mul, div
sum, sub, mul, div=arithmeticop(10,5) #Calling arithmeticop() function

You can see that arithmeticop() returns four variables and when it is called values of variables can be unpacked in sequence.

Share to Your Friend
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Comment