Python User defined functions

26 Jul, 2021
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  
Parameterized functions Default arguments  Keyword arguments  Variable length arguments  Pass by Reference or pass by value?  
Default arguments  
Keyword arguments  
Variable length arguments  
Pass by Reference or pass by value?  
Function with return value  
 
 
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: 
Python3
# Python program to# demonstrate functions # Declaring a functiondef fun():    print("Inside function") # Driver's code# Calling functionfun()
Output:  
Inside 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: 
Python3
# Python program to# demonstrate functions # A simple Python function to check# whether x is even or odddef evenOdd( x ):    if (x % 2 == 0):        print("even")    else:        print("odd")   # Driver codeevenOdd(2)evenOdd(3)
Output:  
even
odd
 
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: 
Python3
# Python program to demonstrate# default argumentsdef myFun(x, y = 50):    print("x: ", x)    print("y: ", y)   # Driver code (We call myFun() with only# argument)myFun(10)
Output:  
x:  10
y:  50
Note: To know more about default arguments click here. 
The idea is to allow caller to specify argument name with values so that caller does not need to remember order of parameters.Example: 
Python3
# Python program to demonstrate Keyword Argumentsdef student(firstname, lastname):      print(firstname, lastname)           # Keyword arguments                  student(firstname ='Geeks', lastname ='Practice')    student(lastname ='Practice', firstname ='Geeks')
Output: 
Geeks Practice
Geeks Practice
 
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: 
Python3
# Python program to illustrate  # *args and **kwargsdef myFun1(*argv):     for arg in argv:         print (arg) def myFun2(**kwargs):     for key, value in kwargs.items():        print ("% s == % s" %(key, value))   # Driver codeprint("Result of * args: ")myFun1('Hello', 'Welcome', 'to', 'GeeksforGeeks') print("\nResult of **kwargs")myFun2(first ='Geeks', mid ='for', last ='Geeks') 
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. 
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: 
Python3
# Python program to# verify pass by reference def myFun(x):    print("Value received:", x, "id:", id(x)) # Driver's codex = 12print("Value passed:", x, "id:", id(x))myFun(x)
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 which 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 codex = 10arr = [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
 
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:  
Python3
# 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 functionres = 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
 
abhishek0719kadiyan
anikakapoor
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.