Function in Python

Function in python is a group of statement that perform some task.  It can be called multiple times and we can also reused the function multiple times in python program.

Basically function helps to programmer to divide the code into small parts to organize the code and avoid repetition of the code.

In Python there are 2 types of function:
  1. Built-in Function
  2. User-Defined Function

How to Create Function:

If you want to use function in your program, there are 3 main parts you have to use:
  • Function Definition
  • Function Return type
  • Function Calling

Function Definition:

In Python to define a function you need to use def keyword. 
Let's see the following syntax:

def function_name(arguments):



Function Return Type:

In Python when you use the return type in function, you should use the return keyword. The return statement used to return a value once at a time.
 Let's see the following syntax:

return expression





Function Calling:

In Python after defining the function you need to call the function. To call the function you use simply the function name with parameters within a pair of parenthesis.
Let's see the following syntax:

function_name (parameter list)

Parameter list are optional, it used as requirement wise. Sometime the function may be without parameter list.


Example 1: Function without return type

def display():
    print("Hello World")
display()


Output:

Hello World
>>> 

 


Example 2: Function with return type

def add(a,b):
    c=a+b
    return c
x=int(input("Enter 1st number:"))
y=int(input("Enter 2nd number:"))
z=add(x,y)
print("Addition of 2 numbers:",z)


Output:

Enter 1st number:5
Enter 2nd number:6
Addition of 2 numbers: 11
>>> 





Function with Argument:

Function argument hold the information which is passed when the function is calling. It can be any type and any number of argument we can pass. The arguments are placed within a pair of parenthesis.



Example: Multiplication of 3 Numbers with argument and return type.

def sum(x,y,z):
    k=x*y*z
    return k
a=int(input("Enter 1st number:"))
b=int(input("Enter 2nd number:"))
c=int(input("Enter 3rd number:"))
d=sum(a,b,c)
print("The multiplication of 3 numbers is:",d)
 

Output:


Enter 1st number: 4
Enter 2nd number: 5
Enter 3rd number: 6
The multiplication of 3 numbers is: 120
>>> 




Comments

Popular Posts