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.
# Declaring a function
def fun():
print("Inside function")
# Driver's code
# Calling function
fun()
Output:
Inside functionPython 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.
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.
# 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
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
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')
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 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.
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:
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.
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
Python User defined functions – FAQs
What is a user-defined function with an example?
A user-defined function in Python is a function that you create yourself to perform a specific task. These functions are defined using the
defkeyword.Example:
def add_numbers(a, b):
"""Function to add two numbers."""
return a + b
# Using the user-defined function
result = add_numbers(5, 3)
print(result) # Output: 8
What is the difference between inbuilt and user-defined functions in Python?
- Inbuilt functions: These are functions that come pre-defined in Python, such as
print(),len(), andsum(). They are ready to use without any need for definition.- User-defined functions: These are functions that you define yourself to perform specific tasks, using the
defkeyword.
What are the disadvantages of user-defined functions in Python?
- Performance overhead: User-defined functions may introduce a slight performance overhead compared to inbuilt functions, as they add an extra layer of function calls.
- Potential for errors: Errors in logic or implementation can lead to bugs and unexpected behavior.
- Maintenance: Custom functions require maintenance and documentation, especially in larger projects.
- Redundancy: If not designed properly, user-defined functions can lead to redundant or duplicated code.
What is the difference between user-defined and predefined functions?
def greet(name):
return f"Hello, {name}!"
- User-defined functions: Created by the programmer to perform specific tasks, using the
defkeyword. Example:- Predefined (inbuilt) functions: Provided by Python, ready to use, and do not require definition. Example:
length = len("example") # len is a predefined function
What is called a user-defined function?
A user-defined function is a function that is written and defined by the programmer to perform specific tasks or calculations. It is defined using the
defkeyword and can accept parameters, contain a body of code, and return values.Example:
def multiply(a, b):
"""Function to multiply two numbers."""
return a * b
# Using the user-defined function
result = multiply(4, 5)
print(result) # Output: 20


