Python User defined functions

A function is a set of statements that take inputs, do some specific computation and produce output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function.

Functions that readily comes with Python are called built-in functions. Python provides built-in functions like print(), etc. but we can also create your own functions. These functions are known as user defines functions.

Table of Content



User defined functions

All the functions that are written by any us comes under the category of user defined functions. Below are the steps for writing user defined functions in Python.

  • In Python, def keyword is used to declare user defined functions.
  • An indented block of statements follows the function name and arguments which contains the body of the function.

Syntax:

def function_name():
    statements
    .
    .

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to
# demonstrate functions 
  
# Declaring a function
def fun():
    print("Inside function")
  
# Driver's code
# Calling function
fun()

chevron_right


Output:

Inside function

Parameterized Function

The function may take arguments(s) also called parameters as input within the opening and closing parentheses, just after the function name followed by a colon.

Syntax:

def function_name(argument1, argument2, ...):
    statements
    .
    .

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to
# demonstrate functions
  
# A simple Python function to check 
# whether x is even or odd 
def evenOdd( x ): 
    if (x % 2 == 0): 
        print("even")
    else
        print("odd")
    
# Driver code 
evenOdd(2
evenOdd(3)

chevron_right


Output:

even
odd

Default arguments

A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument.The following example illustrates Default arguments.

Example:


filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate 
# default arguments 
def myFun(x, y = 50): 
    print("x: ", x) 
    print("y: ", y) 
    
# Driver code (We call myFun() with only 
# argument) 
myFun(10

chevron_right


Output:

x:  10
y:  50

Note: To know more about default arguments click here.

Keyword arguments

The idea is to allow caller to specify argument name with values so that caller does not need to remember order of parameters.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate Keyword Arguments 
def student(firstname, lastname):  
     print(firstname, lastname)  
      
      
# Keyword arguments                   
student(firstname ='Geeks', lastname ='Practice')     
student(lastname ='Practice', firstname ='Geeks'

chevron_right


Output:

Geeks Practice
Geeks Practice

Variable length arguments

We can have both normal and keyword variable number of arguments.

  • The special syntax *args in function definitions in Python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list.
  • The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is because the double star allows us to pass through keyword arguments (and any number of them).

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to illustrate   
# *args and **kwargs
def myFun1(*argv):  
    for arg in argv:  
        print (arg) 
  
def myFun2(**kwargs):  
    for key, value in kwargs.items(): 
        print ("% s == % s" %(key, value)) 
    
# Driver code 
print("Result of * args: ")
myFun1('Hello', 'Welcome', 'to', 'GeeksforGeeks'
  
print("\nResult of **kwargs")
myFun2(first ='Geeks', mid ='for', last ='Geeks')  

chevron_right


Output:

Result of *args: 
Hello
Welcome
to
GeeksforGeeks

Result of **kwargs
mid == for
first == Geeks
last == Geeks

Note: To know more about variable length arguments click here.

Pass by Reference or pass by value?

One important thing to note is, in Python every variable name is a reference. When we pass a variable to a function, a new reference to the object is created. Parameter passing in Python is same as reference passing in Java. To confirm this Python’s built-in id() function is used in below example.


Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to
# verify pass by reference
  
def myFun(x):
    print("Value recieved:", x, "id:", id(x))
  
# Driver's code
x = 12
print("Value passed:", x, "id:", id(x))
myFun(x)

chevron_right


Output:

Value passed: 12 id: 10853984
Value recieved: 12 id: 10853984

If the value of the above variable is changed inside a function, then it will create a different variable as a number which is immutable. However, if a mutable list object is modified inside the function, the changes are reflected outside the function also.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

def myFun(x, arr):
    print("Inside function")
  
    # changing integer will
    # Also change the reference 
    # to the variable
    x += 10
    print("Value received", x, "Id", id(x))
  
    # Modifying mutable objects
    # will also be reflected outside 
    # the function 
    arr[0] = 0
    print("List received", arr, "Id", id(arr))
  
# Driver's code
x = 10
arr = [1, 2, 3]
  
print("Before calling function")
print("Value passed", x, "Id", id(x))
print("Array passed", arr, "Id", id(arr))
print()
  
myFun(x, arr)
  
print("\nAfter calling function")
print("Value passed", x, "Id", id(x))
print("Array passed", arr, "Id", id(arr))

chevron_right


Output:

Before calling function
Value passed 10 Id 10853920
Array passed [1, 2, 3] Id 139773681420488

Inside function
Value received 20 Id 10854240
List received [0, 2, 3] Id 139773681420488

After calling function
Value passed 10 Id 10853920
Array passed [0, 2, 3] Id 139773681420488

Function with return value

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.
A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned.

Syntax:

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

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to 
# demonstrate return statement 
   
def add(a, b):
   
    # returning sum of a and b
    return a + b
   
def is_true(a):
   
    # returning boolean of a
    return bool(a)
   
# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
   
res = is_true(2<5)
print("\nResult of is_true function is {}".format(res))

chevron_right


Output:

Result of add function is 5

Result of is_true function is True


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.