Friday, December 27, 2024
Google search engine
HomeLanguagesPython User defined functions

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 come 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 

Python User-defined functions

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

  • In Python, a 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: Here we have created the fun function and then called the fun() function to print the statement.

Python3




# Declaring a function
def fun():
    print("Inside function")
 
# Driver's code
# Calling function
fun()


Output: 

Inside function

Python 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:

A simple Python function to check whether x is even or odd.

Python3




def evenOdd( x ):
    if (x % 2 == 0):
        print("even")
    else:
        print("odd")
   
# Driver code
evenOdd(2)
evenOdd(3)


Output: 

even
odd

Python 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: We call myFun() with the only argument.

Python3




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


Output:

x:  10
y: 50

Note: To know more about default arguments click here.

Python Keyword arguments

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

Example: Python program to demonstrate Keyword Arguments 

Python3




def student(firstname, lastname): 
     print(firstname, lastname) 
     
     
# Keyword arguments                  
student(firstname ='Geeks', lastname ='Practice')    
student(lastname ='Practice', firstname ='Geeks')


Output:

Geeks Practice
Geeks Practice

Python Variable Length Arguments

We can have both normal and keyword variable numbers 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 that the double star allows us to pass through keyword arguments (and any number of them). 

Example: Python program to illustrate  *args and **kwargs

Python3




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', 'Lazyroar')
 
print("\nResult of **kwargs")
myFun2(first ='Geeks', mid ='for', last ='Geeks'


Output:

Result of *args: 
Hello
Welcome
to
Lazyroar

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 in Python

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 the same as reference passing in Java. To confirm this Python’s built-in id() function is used in the below example.

Example:

Python program to verify pass-by-reference.

Python3




def myFun(x):
    print("Value received:", x, "id:", id(x))
 
# Driver's code
x = 12
print("Value passed:", x, "id:", id(x))
myFun(x)


Output

Value passed: 12 id: 11094656
Value received: 12 id: 11094656

Output: 

Value passed: 12 id: 10853984
Value received: 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 that is immutable. However, if a mutable list object is modified inside the function, the changes are reflected outside the function also.

Example:

Python3




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))


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

Python Function with return value

Sometimes we might need the result of the function to be used in further processes. Hence, a function should also return a value when it finishes its execution. This can be achieved by a 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: 

Python program to demonstrate return statement.

Python3




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))


Output: 

Result of add function is 5

Result of is_true function is True

RELATED ARTICLES

Most Popular

Recent Comments