Python User Defined Function

Table Of Contents:

  1. What Is A User Defined Function?
  2. Creating User Defined Functions.
  3. Calling User Defined Functions.
  4. Function With Return Type.
  5. Parameterized Functions.
  6. Default Arguments.
  7. Keyword Arguments.
  8. Variable Length Arguments.
  9. Pass By Reference Or Pass By Value.

(1) What Is A User Defined Function?

  • A function is a set of statements that take inputs, do some specific computation and produce output.
  • The function which is written by the user is called User Defined Function.
  • The function which comes by default from the programming language are called inbuilt functions.
  • The sole purpose of creating function is to put some commonly or repeatedly done tasks together, so that instead of writing the same code again and again for different inputs, we can call the function.

(2) Creating User Defined Function?

  • def keyword is used to create a User Defined Function.
  • After def give a space and write your function name.
  • After your function name put open and close parenthesis ( ).
  • Put a colon ( : ) after parenthesis ( ).
  • Press enter .
  • Write your own code under the same indentation.

Syntax:

def function_name():
    #Your Code Goes Here

Example-1

def sum_function():
    x = 10
    y = 20
    sum = x + y
    print(sum)

Example-2

def address():
    Name = 'Abhipsha Pattnaik'
    Town = 'Puri, Odisha'
    State = 'Odisha'
    Country = 'India'
    print(Name,Town,State,Country)

(3) Calling A User Defined Function.

  • You can call a User Defined Function by its name.
  • Use the function name and open and close parenthesis ( ) to call the function.
  • When you call the function, the code inside it will be executed.

Syntax:

function_name()

Example-1

def sum_function():
    x = 10
    y = 20
    sum = x + y
    print(sum)

sum_function() # Calling The Function.
Output:
30

Example-2

def address():
    Name = 'Abhipsha Pattnaik'
    Town = 'Puri, Odisha'
    State = 'Odisha'
    Country = 'India'
    print(Name,Town,State,Country)
    
address() # Calling The Function.
Output:
Abhipsha Pattnaik Puri, Odisha Odisha India

(4) Function With Return Type

  • Sometimes we might need the result of the function to be used in further process.
  • Hence, a function should also returns a value when it finishes it’s execution.
  • This can be achieved by return statement.
  • You can use the ‘return’ keyword to return something from a function.

Syntax:

def fun():
    statements
    .
    .
    return [expression]

Example-1

def add(x,y):
    sum = x + y
    return sum #Returning A Value

value = add(10,40) #Receiving Values

print(value)
Output:
50

Example-2

def student():
    name = 'Abhipsa Pattnaik'
    roll_no = 143
    return name,roll_no #Returning Values

name,roll_no = student() #Receiving Values

print(name,roll_no)
Output:
Abhipsa Pattnaik 143

Note:

  • You can return multiple values by separating them with a comma ( , ).

(5) Parameterized Function .

  • The function which takes arguments ( parameters ) as input are called parameterized function.
  • The argument are written within the opening and closing parentheses () , just after the function name followed by a colon : .

Syntax:

def function_name(arg1,arg2,....):
    <Your Code>

Example-1

def sum_function(x,y):
    sum = x + y
    print(sum)

sum_function(100,200)
Output:
300

Note:

  • Here x and y are passed as parameters to sum_function().
  • Hence it is called parameterized function.

Example-2

def address(Name,Town,State,Country):
    print(Name,Town,State,Country)

address("Abhipsha Pattnaik", "Puri", "Odisha" , "India")
Output:
Abhipsha Pattnaik Puri Odisha India

Note:

  • Here Name,Town,State,Country are passed as an arguments to address function.

(6) Default Arguments.

  • You can also set the default value of the arguments while defining the function.
  • When you don’t pass any values the default value will be taken for that argument.

Example-1

def sum_function(x,y=30):
    sum = x + y
    print(sum)

sum_function(20)
Output:
50

Note:

  • Here default value of y = 30 has taken as it’s value.

Example-2

def sum_function(x,y=30):
    sum = x + y
    print(sum)

sum_function(20,50)
Output:
70

Note:

  • Here I am defining a default value of 30 and passing a value of 50.
  • So the passed value will be considered as its value not the default value.

(7) Keyword Arguments.

  • Sometimes you don’t know in which order the arguments are mentioned in the function definition.
  • While you are calling a function you must pass the arguments in that order only.
  • Or else the argument mismatch will happen.
  • To avoid this issue, you can use keyword arguments which allow caller to specify argument name with values so that caller does not need to remember order of parameters.

Example-1: Without Keyword Arguments

def student(name, rollno): 
     print('Name: ',name,'\nRoll No:', rollno)
    
student(84567,'Abhispa Pattnaik')
Output:
Name:  84567 
Roll No: Abhispa Pattnaik

Note:

  • Here you have passed the arguments in a wrong order.
  • In place of name you have passed roll no and in place of roll no you have passed name.
  • To avoid this issue we can use Keyword Arguments.

Example-2: With Keyword Arguments

def student(name, rollno): 
     print('Name: ',name,'\nRoll No:', rollno)

# Keyword Arguments   
student(rollno = 84567, name = 'Abhispa Pattnaik') 
Output:
Name:  Abhispa Pattnaik 
Roll No: 84567

Note:

  • While calling the function I have passed, variable name and it’s values like rollno = 84567,name = ‘Abhispa Pattnaik’.

  • This is called Keyword Argument passing.

(8) Variable Length Arguments.

  • Sometimes you will not know how many arguments you want to pass to a function it will be decided in run time.
  • At that time you can use variable length arguments.
  • To implement variable length arguments you have to use special syntax as below.
  • *args for normal arguments like (name,rollno,place).
  • **kargs for keyword arguments like (name=’Abhispa’,rollno=64728,place=’Puri’).

Example-1: *args Variable Length Arguments

def countries(*args):
    for i in args:
        print(i)

countries('India','Australia','Finland','Poland')
Output:
India
Australia
Finland
Poland

Example-2: **kargs Variable Length Arguments

def countries(**kargs):
    for key,value in kargs.items():
        print('Key:',key)
        print('Value:',value)

countries(Rank1 = 'India',Rank2 = 'Australia',Rank3 = 'Finland',Rank4 = 'Poland')
Output:
Key: Rank1
Value: India
Key: Rank2
Value: Australia
Key: Rank3
Value: Finland
Key: Rank4
Value: Poland

(9) Pass By Reference or Pass By Value.

  • Pass By Value: While you are calling the function you are passing the parameters value only. This method of calling is called Pass By Value Calling.
  • Pass By Value: Any changes made to the passing variable will not change the original variable.
  • Pass By Reference: Here reference means address of the variable. While calling the function you are passing the memory location of the variable.
  • Pass By Reference: Any changes made to the passing variable will reflect the original variable.
  • One important thing to note is, in Python every variable name is a reference.

Example-1:Pass By Value

mark = 76
print('Before:','Mark:',mark)

def exam(mark):
    mark = 88 #Creating A Local Variable It will have different address.

exam(mark)

print('After:','Mark:',mark)
Output:
Before: Mark: 76
After: Mark: 76

Note:

  • As the number data type is immutable in nature it will create a new memory location in memory.
  • Hence the original mark value has not changed.

Example-2:Pass By Reference

mark = 76
grades = ['A','B','C']
print('Before:','Mark:',mark,'\nGrades:',grades)

def exam(mark,grades):
    mark = 88 #Creating A Local Variable It will have different address.
    grades.append('D')

exam(mark,grades)

print('After:','Mark:',mark,'\nGrades:',grades)
Output:
Before: Mark: 76 
Grades: ['A', 'B', 'C']
After: Mark: 76 
Grades: ['A', 'B', 'C', 'D']

Note:

  • As the list is mutable data type hence, changing the value inside the function has affected the value outside of the function.

Leave a Reply

Your email address will not be published. Required fields are marked *