Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
User-defined functions
2.1.
Python
2.2.
Python
3.
Parameterized functions
3.1.
Python
3.2.
Python
3.3.
Python
4.
Default arguments
4.1.
Python
4.2.
Python
4.3.
Python
5.
Keyword arguments
5.1.
Python
5.2.
Python
5.3.
Python
6.
Variable length arguments:
6.1.
Python
6.2.
Python
6.3.
Python
6.4.
Python
7.
Pass by Reference or pass by value?
7.1.
Python
7.2.
Python
8.
Function with return value
8.1.
Python
8.2.
Python
8.3.
Python
9.
Frequently Asked Questions
9.1.
What is the difference between a function & a method in Python?
9.2.
Can a function in Python return multiple values?
9.3.
What happens if a function doesn't have a return statement?
10.
Conclusion
Last Updated: Jul 20, 2024
Easy

User Defined Functions in Python

Author Rahul Singh
0 upvote

Introduction

Functions are an essential part of programming in Python. They allow us to break down complex problems into smaller, more manageable pieces of code. User-defined functions are functions that we create ourselves to perform specific tasks. 

User Defined Functions in Python

In this article, we will talk about the different types of user-defined functions in Python, like parameterized functions, default arguments, keyword arguments, & variable length arguments. We will also discuss the concept of pass by reference & pass by value, as well as functions with return values. 

User-defined functions

In Python, we can create our own functions to perform specific tasks. These functions are called user-defined functions. To define a function, we use the "def" keyword followed by the function name & a set of parentheses. Inside the parentheses, we can specify any parameters that the function will take. The function body is indented below the function definition.

Let’s see an example of a simple user-defined function that takes no parameters & prints a message:

  • Python

Python

def greet():

   print("Hello, world!")


To call this function, we simply write its name followed by a set of parentheses:

  • Python

Python

greet()


Output

Hello, world!


User-defined functions allow us to encapsulate a block of code that we can reuse throughout our program. This makes our code more modular, readable, & easier to maintain.

Parameterized functions

Parameterized functions are functions that take one or more parameters (also called arguments) as input. These parameters allow us to pass values into the function, which can then be used inside the function body. 

Let’s see an example of a parameterized function that takes two numbers as input & prints their sum:

  • Python

Python

def add_numbers(num1, num2):

   sum = num1 + num2

   print(f"The sum of {num1} & {num2} is {sum}")


To call this function, we pass in two numbers as arguments:

  • Python

Python

add_numbers(5, 7)


Output

The sum of 5 & 7 is 12


We can also assign the arguments to variables before passing them into the function:

  • Python

Python

a = 10

b = 20

add_numbers(a, b)


Output

The sum of 10 & 20 is 30


Parameterized functions make our code more flexible & reusable, as we can pass in different values each time we call the function.

Default arguments

Default arguments are parameters that have a default value assigned to them in the function definition. If no argument is passed for that parameter when the function is called, the default value is used.

Here's an example of a function with a default argument:

  • Python

Python

def greet(name, greeting="Hello"):

   print(f"{greeting}, {name}!")


In this function, the `name` parameter is required, but the `greeting` parameter has a default value of "Hello". If we call the function with only one argument, the default value will be used for `greeting`:

  • Python

Python

greet("Rahul")

Output

Hello, Rahul!


We can also override the default value by passing in a second argument:

  • Python

Python

greet("Rinki", "Hi")


Output

Hi, Rinki!


Default arguments can make our functions more versatile & save us from having to pass in the same value every time if we have a commonly used default.

Keyword arguments

Keyword arguments are a way to pass arguments to a function using the parameter names instead of relying on their position. When calling a function with keyword arguments, we specify the parameter name followed by an equals sign & the value we want to pass.

Here's an example of a function that takes two keyword arguments:

  • Python

Python

def student_info(name, age):

   print(f"Name: {name}, Age: {age}")


We can call this function using keyword arguments like this:

  • Python

Python

student_info(age=21, name="Harsh")


Output

Name: Harsh, Age: 21


Notice that we don't have to pass the arguments in the same order as they are defined in the function. We can specify them in any order, as long as we use the correct parameter names.

We can also mix positional & keyword arguments, but the positional arguments must come first:

  • Python

Python

student_info("Sanjana", age=20)


Output

Name: Sanjana, Age: 20


Keyword arguments can make our code more readable, especially when dealing with functions that have many parameters.

Variable length arguments:

Sometimes we may need to pass a varying number of arguments to a function. In Python, we can handle this using variable length arguments, also known as `*args` & `**kwargs`.

`*args` allows us to pass a variable number of non-keyword arguments to a function. The `*` before the parameter name tells Python to pack all the arguments into a tuple.

Here's an example of a function that takes variable length arguments using `*args`:

  • Python

Python

def sum_numbers(*args):

   total = 0

   for num in args:

       total += num

   return total


We can call this function with any number of arguments:

  • Python

Python

result1 = sum_numbers(1, 2, 3)

result2 = sum_numbers(4, 5, 6, 7, 8)

print(result1)

print(result2) 


Output

6
30


`**kwargs` allows us to pass a variable number of keyword arguments to a function. The `**` before the parameter name tells Python to pack all the keyword arguments into a dictionary.

Here's an example of a function that takes variable length keyword arguments using `**kwargs`:

  • Python

Python

def print_student_info(**kwargs):

   for key, value in kwargs.items():

       print(f"{key}: {value}")


We can call this function with any number of keyword arguments:

  • Python

Python

print_student_info(name="Ravi", age=22, city="Delhi")


Output

name: Ravi
age: 22
city: Delhi


Variable length arguments give us flexibility when we don't know in advance how many arguments a function will need to handle.

Pass by Reference or pass by value?

In Python, when we pass arguments to a function, they are passed by reference. This means that if we modify a mutable object (like a list or dictionary) inside a function, the changes will be reflected outside the function as well.

For example:

  • Python

Python

def modify_list(my_list):

   my_list.append(4)

   print("Inside the function:", my_list)

numbers = [1, 2, 3]

modify_list(numbers)

print("Outside the function:", numbers)


Output

Inside the function: [1, 2, 3, 4]
Outside the function: [1, 2, 3, 4]


As we can see, the changes made to the list inside the function are visible outside the function as well.

However, when we reassign a new value to a parameter inside a function, it doesn't affect the original variable outside the function. This is because the parameter inside the function is just a reference to the original object, not the object itself.

Here's an example:

  • Python

Python

def reassign_value(num):

   num = 20

   print("Inside the function:", num)

number = 10

reassign_value(number)

print("Outside the function:", number)


Output

Inside the function: 20
Outside the function: 10


In this case, reassigning `num` inside the function doesn't change the value of `number` outside the function.

Function with return value

So far, we have seen functions that perform actions, such as printing output or modifying objects. However, functions can also return values that we can use in our program. To return a value from a function, we use the `return` statement followed by the value we want to return.

Here's an example of a function that takes two numbers as input & returns their sum:

  • Python

Python

def add_numbers(num1, num2):

   sum = num1 + num2

   return sum


To use the value returned by the function, we can assign it to a variable or use it directly in an expression:

  • Python

Python

result = add_numbers(5, 7)

print("The sum is:", result)

print("The sum is:", add_numbers(10, 20))


Output

The sum is: 12
The sum is: 30


We can also return multiple values from a function using tuples:

  • Python

Python

def get_name_and_age():

   name = "Mehak"

   age = 19

   return name, age

student_name, student_age = get_name_and_age()

print("Name:", student_name)

print("Age:", student_age)


Output

Name: Mehak
Age: 19


Functions with return values allow us to write more modular & reusable code, as we can use the returned values in different parts of our program.

Frequently Asked Questions

What is the difference between a function & a method in Python?

A function is a standalone block of code that performs a specific task, while a method is a function that belongs to a class. Methods operate on the attributes of an object & can access & modify its state.

Can a function in Python return multiple values?

Yes, a function in Python can return multiple values. To do this, we can return a tuple containing the values we want to return. The tuple can then be unpacked into individual variables when the function is called.

What happens if a function doesn't have a return statement?

If a function doesn't have a return statement, it will automatically return None when it reaches the end of the function body. None is a special value in Python that represents the absence of a value.

Conclusion

In this article, we have learned about user-defined functions in Python. We talked about the different types of functions, including parameterized functions, functions with default arguments, keyword arguments, & variable length arguments. We also discussed the concept of pass by reference & pass by value in Python, as well as functions with return values. User-defined functions are a powerful tool in Python that allow us to write modular, reusable, & maintainable code.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass