The Wayback Machine - https://web.archive.org/web/20240718182708/https://www.geeksforgeeks.org/python-user-defined-functions/
Open In App

Python User defined functions

Last Updated : 03 Jul, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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.

Python
# 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.

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

Python
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

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

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

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

Python
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 def keyword.

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(), and sum(). 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 def keyword.

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 def keyword. 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 def keyword 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


Similar Reads

How to Write Spark UDF (User Defined Functions) in Python ?
In this article, we will talk about UDF(User Defined Functions) and how to write these in Python Spark. UDF, basically stands for User Defined Functions. The UDF will allow us to apply the functions directly in the dataframes and SQL databases in python, without making them registering individually. It can also help us to create new columns to our
4 min read
User-defined Exceptions in Python with Examples
Prerequisite: This article is an extension to Exception Handling. In this article, we will try to cover How to Define Custom Exceptions in Python with Examples. Example: class CustomError(Exception): pass raise CustomError("Example of Custom Exceptions in Python") Output: CustomError: Example of Custom Exceptions in Python Python throws errors and
4 min read
User Defined Data Structures in Python
In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures: Non-primitive data types: Python has list, set, and dictionary as its non-prim
4 min read
Sorting objects of user defined class in Python
The following article discusses how objects of a user-defined class can be arranged based on any of the variables of the class, which obviously will hold some value for every object. So far, we are aware of how we can sort elements of a list, the concept here is more or less the same as, except it is a step forward or we can say it is an advanced v
5 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
Python VLC Instance - Enumerate the defined audio output devices
In this article we will see how we can get the enumerate audio output devices from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance obje
3 min read
Viewing all defined variables in Python
In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code. Method 1: Using dir() function dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all decl
5 min read
Why do Python lambda defined in a loop with different values all return the same result?
In this article, we are going to learn why Python lambda defined in a loop with different values all return the same result. In this article, we will explore the reasons behind this behavior and discuss how to avoid it. We will start by looking at how lambda functions are defined and executed, and how they capture the values of variables that are u
6 min read
Python - Check if String Contain Only Defined Characters using Regex
In this article, we are going to see how to check whether the given string contains only a certain set of characters in Python. These defined characters will be represented using sets. Examples: Input: ‘657’ let us say regular expression contains the following characters- (‘78653’) Output: Valid Explanation: The Input string only consists of charac
2 min read
Nameerror: name self is not defined in Python
Python, a dynamically typed and object-oriented programming language, is lauded for its simplicity and readability. However, even the most seasoned developers can encounter stumbling blocks, and one such common hurdle is the "NameError: name 'self' is not defined." In this article, we will see how to fix Nameerror: Name 'self' is not defined in Pyt
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg