Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Python Function Declaration
3.
Types of Functions in Python
3.1.
Built-in Functions
3.2.
Python
3.3.
User-defined Functions
3.4.
Python
4.
Creating a Function in Python
5.
Calling a Function in Python
5.1.
Python
6.
Python Function with Parameters
6.1.
Python
7.
Python Function Syntax with Parameters
7.1.
Python
8.
Python Function Arguments
9.
Default Arguments
9.1.
Syntax
9.2.
Example
9.3.
Python
10.
Keyword Arguments (Named Arguments)
10.1.
Syntax
10.2.
Example:
10.3.
Python
11.
Positional Arguments
11.1.
Syntax
11.2.
Example
11.3.
Python
12.
Arbitrary Arguments (Variable-length Arguments)
12.1.
Syntax
12.2.
Example
12.3.
Python
13.
b. **kwargs (Keyword Arbitrary Arguments)
13.1.
Syntax
13.2.
Example
13.3.
Python
14.
Python Function within Functions
14.1.
Syntax
14.2.
Example
14.3.
Python
15.
Anonymous Functions in Python (Lambda Functions):
15.1.
Syntax
15.2.
Example 1
15.3.
Python
15.4.
Example 2
15.5.
Python
15.6.
Example 3
15.7.
Python
16.
Recursive Functions in Python
16.1.
Syntax
16.2.
Example 1 (Factorial)
16.3.
Python
16.4.
Example 2 (Fibonacci Sequence):
16.5.
Python
17.
Return Statement in Python Function:
17.1.
Syntax
17.2.
Example 1
17.3.
Python
17.4.
Example 2
17.5.
Python
17.6.
Example 3:
17.7.
Python
18.
Pass by Reference and Pass by Value in Python:
18.1.
Pass by Reference
18.1.1.
Example
18.2.
Python
18.3.
Pass by Value
18.3.1.
Example:
18.4.
Python
18.4.1.
Example:
18.5.
Python
19.
Frequently Asked Questions
19.1.
What is the difference between a parameter and an argument in Python functions?
19.2.
Can a Python function return multiple values?
19.3.
What happens if a function doesn't have a return statement?
20.
Conclusion
Last Updated: Jun 30, 2024
Easy

How to Define a Function in Python?

Author Ravi Khorwal
0 upvote

Introduction

Functions are a fundamental concept in Python programming. They allow you to group related code together and reuse it throughout your program. Functions help make your code more organized, readable, and maintainable. 

How to Define a Function in Python

In this article, we will learn how to define and use functions in Python. We will discuss the basics of function declaration, different types of functions, and how to pass arguments to functions. 

Python Function Declaration

To define a function in Python, you use the "def" keyword followed by the function name and a set of parentheses. If the function takes any parameters, you specify them inside the parentheses. After the parentheses, you add a colon to indicate the start of the function block. The function block contains the code that will be executed when the function is called.

Here's the basic syntax for declaring a function in Python:

def function_name(parameters):
# function body
# code to be executed


For example, let's define a simple function that prints "Hello, World!":

def greet():
print("Hello, World!")


In this example, we defined a function named "greet" using the "def" keyword. The function doesn't take any parameters, so the parentheses are empty. The function body consists of a single line of code that prints "Hello, World!" when the function is called.

Types of Functions in Python

In Python, there are two main types of functions:

Built-in Functions

Python provides a set of built-in functions that are readily available for use. These functions are part of the Python standard library and can be used without requiring any additional imports. Examples of built-in functions include print(), len(), range(), and type().

For example, to find the length of a list, you can use the len() function:

  • Python

Python

my_list = [1, 2, 3, 4, 5]

length = len(my_list)

print(length) 

Output

 5

User-defined Functions

User-defined functions are functions that you create yourself to perform specific tasks in your program. These functions are defined using the "def" keyword, as shown in the previous section. User-defined functions allow you to encapsulate a block of code and reuse it multiple times throughout your program.

Here's an example of a user-defined function that calculates the area of a circle:

  • Python

Python

def circle_area(radius):

area = 3.14 * radius ** 2

return area

result = circle_area(5)

print(result) 

Output: 

78.5


In this example, we defined a function named "circle_area" that takes the radius of a circle as a parameter. The function calculates the area using the formula π * r^2 and returns the result. We can then call this function with different radius values to calculate the area of various circles.

Creating a Function in Python

To create a function in Python, you follow these steps:

  1. Use the "def" keyword followed by the function name.
     
  2. Add a set of parentheses after the function name.
     
  3. If the function takes parameters, specify them inside the parentheses.
     
  4. Add a colon after the parentheses to indicate the start of the function block.
     
  5. Indent the function body (the code inside the function) with four spaces or a tab.
     
  6. Optionally, use the "return" statement to specify the value(s) the function should return.
     

Example that shows the process of creating a function:

def add_numbers(a, b):
sum = a + b
return sum


In this example, we created a function named "add_numbers" that takes two parameters, "a" and "b". The function calculates the sum of these two numbers and assigns it to the variable "sum". Finally, the function uses the "return" statement to send the value of "sum" back to the caller.

Let's create another function that greets a person by name:

def greet_person(name):
greeting = "Hello, " + name + "!"
print(greeting)


This function, named "greet_person", takes a single parameter "name". Inside the function, we create a greeting message by concatenating the string "Hello, " with the value of "name" and an exclamation mark. The function then prints the greeting message using the "print()" function.

Calling a Function in Python

Once you have defined a function, you can call it from anywhere in your program. To call a function, you simply use the function name followed by a set of parentheses. If the function requires arguments, you pass them inside the parentheses.

Let's see how to call the functions we created in the previous examples:

  • Calling the add_numbers function
result = add_numbers(5, 3)
print(result)  


Output 

8

 

  • Calling the greet_person function
greet_person("Rahul")  


Output: 

Hello, Rahul!


In the first example, we call the "add_numbers" function and pass two arguments, 5 and 3, inside the parentheses. The function returns the sum of these numbers, which is then assigned to the variable "result". We print the value of "result" to display the sum.

In the second example, we call the "greet_person" function and pass the name "Rahul" as an argument. The function prints the greeting message "Hello, Rahul!" to the console.

You can call a function multiple times with different arguments to perform the same operation on different data. For example:

  • Calling the add_numbers function multiple times
  • Python

Python

result1 = add_numbers(2, 3)

result2 = add_numbers(10, 7)

result3 = add_numbers(4, 9)

print(result1) 

print(result2) 

print(result) 

Output:

5 
17
13

 

In this example, we call the "add_numbers" function three times with different pairs of numbers. Each time, the function returns the sum of the provided numbers, and we assign the results to different variables for later use.

Python Function with Parameters

Functions in Python can accept parameters, which are values passed to the function when it is called. Parameters allow you to provide input to the function, making it more flexible and reusable. The function can then use these parameters to perform specific operations or calculations.

Let's create a function that calculates the area of a rectangle:

def rectangle_area(length, width):
area = length * width
return area


In this example, the "rectangle_area" function takes two parameters: "length" and "width". These parameters represent the length and width of the rectangle, respectively. Inside the function, we calculate the area by multiplying the length and width and assign the result to the variable "area". Finally, we use the "return" statement to send the calculated area back to the caller.

To call this function and provide the necessary parameters, you would do something like this:

result = rectangle_area(5, 3)
print(result)  


Output: 

15

In this case, we call the "rectangle_area" function with the arguments 5 and 3, representing the length and width of the rectangle. The function calculates the area (5 * 3 = 15) and returns the result, which is then assigned to the variable "result". We print the value of "result" to display the calculated area.

You can call the function multiple times with different values for the parameters:

  • Python

Python

area1 = rectangle_area(4, 6)

area2 = rectangle_area(2, 8)

area3 = rectangle_area(3, 3)

print(area1) 

print(area2) 

print(area3) 


Output

24
16
 9


Each time we call the "rectangle_area" function with different length and width values, it calculates and returns the corresponding area.

Python Function Syntax with Parameters

The syntax for defining a function with parameters in Python is as follows:

def function_name(parameter1, parameter2, ...):
# function body
# code to be executed
return value (optional)


Let’s discuss the components of the syntax:

  • "def" is the keyword used to define a function.
     
  • "function_name" is the name you give to your function. Choose a descriptive name that reflects what the function does.
     
  • Inside the parentheses "()", you specify the parameters separated by commas. These are the values that the function expects to receive when it is called.
     
  • After the parentheses, add a colon ":" to indicate the start of the function block.
     
  • The function body is indented (usually by four spaces) and contains the code that will be executed when the function is called.
     
  • Optionally, you can use the "return" statement to specify the value(s) the function should return to the caller.
     

Let's create a function that takes two numbers as parameters and returns their average:

def calculate_average(num1, num2):
average = (num1 + num2) / 2
return average

In this example, the function is named "calculate_average", and it takes two parameters: "num1" and "num2". Inside the function, we calculate the average by adding "num1" and "num2" and dividing the result by 2. The calculated average is then returned using the "return" statement.

To call this function and provide the necessary parameters, you would do something like this:

  • Python

Python

result = calculate_average(5, 7)

print(result) 


Output

6.0


In this case, we call the "calculate_average" function with the arguments 5 and 7. The function calculates the average (5 + 7) / 2 = 6.0 and returns the result, which is then assigned to the variable "result". We print the value of "result" to display the calculated average.

Python Function Arguments

Python functions can accept different types of arguments, which allow you to pass values to the function in various ways. The four types of function arguments in Python are:

  1. Default arguments
     
  2. Keyword arguments (named arguments)
     
  3. Positional arguments
     
  4. Arbitrary arguments (variable-length arguments *args and **kwargs)
     

Let's discuss each type of argument in detail.

Default Arguments

Default arguments are parameters that have a default value assigned to them in the function definition. If no value is provided for a default argument when the function is called, the default value is used. This allows you to make certain parameters optional.

Syntax

def function_name(parameter1, parameter2=default_value):
# function body

Example

  • Python

Python

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

print(message + ", " + name + "!")

greet("Rahul") 

greet("Rinki", "Hi")


Output

Hello, Rahul!
Hi, Rinki!


In this example, the "greet" function has two parameters: "name" and "message". The "message" parameter has a default value of "Hello". If no value is provided for "message" when calling the function, the default value is used.

Keyword Arguments (Named Arguments)

Keyword arguments allow you to pass values to a function using the parameter names. This makes the function call more readable and helps avoid confusion about the order of arguments.

Syntax

def function_name(parameter1, parameter2):
# function body
function_name(parameter2=value2, parameter1=value1)

Example:

  • Python

Python

def student_info(name, age, grade):

print("Name:", name)

print("Age:", age)

print("Grade:", grade)

student_info(age=15, grade=9, name="Harsh")


Output

Name: Harsh
Age: 15
Grade: 9


In this example, the "student_info" function takes three parameters: "name", "age", and "grade". When calling the function, we use keyword arguments to specify the values for each parameter. The order of the arguments doesn't matter since we are using the parameter names.

Positional Arguments

Positional arguments are the most common type of arguments in Python. They are passed to a function based on their position or order. The values are matched to the parameters in the function definition based on their position.

Syntax

def function_name(parameter1, parameter2):
# function body
function_name(value1, value2)

Example

  • Python

Python

def student_info(name, age, grade):

print("Name:", name)

print("Age:", age)

print("Grade:", grade)

student_info("Sanjana", 14, 8)


Output:

Name: Sanjana
Age: 14
Grade: 8


In this example, the "student_info" function takes three parameters: "name", "age", and "grade". When calling the function, we provide the values for each parameter in the same order as they are defined in the function. The first value "Sanjana" is assigned to the "name" parameter, the second value 14 is assigned to the "age" parameter, and the third value 8 is assigned to the "grade" parameter.

Arbitrary Arguments (Variable-length Arguments)

Arbitrary arguments allow a function to accept any number of arguments. There are two types of arbitrary arguments:

a. *args (Non-Keyword Arbitrary Arguments):


*args allows a function to accept any number of positional arguments. The arguments are packed into a tuple within the function.

Syntax

def function_name(*args):
# function body
function_name(value1, value2, value3, ...)

Example

  • Python

Python

def sum_numbers(*args):

total = 0

for num in args:

total += num

return total

result = sum_numbers(1, 2, 3, 4, 5)

print(result) 

 

Output:

 15


In this example, the "sum_numbers" function accepts any number of arguments using *args. Inside the function, the arguments are packed into a tuple named "args". We can then iterate over the tuple and perform operations on the arguments. In this case, we calculate the sum of all the numbers passed to the function.

b. **kwargs (Keyword Arbitrary Arguments)

**kwargs allows a function to accept any number of keyword arguments. The arguments are packed into a dictionary within the function.

Syntax

def function_name(**kwargs):
# function body
function_name(key1=value1, key2=value2, ...)

Example

  • Python

Python

def print_info(**kwargs):

for key, value in kwargs.items():

print(key + ":", value)

print_info(name="Ravi", age=16, city="Delhi")


Output

name: Ravi
age: 16
city: Delhi


In this example, the "print_info" function accepts any number of keyword arguments using **kwargs. Inside the function, the arguments are packed into a dictionary named "kwargs". We can then iterate over the dictionary and access the key-value pairs. In this case, we print each key-value pair.

Python Function within Functions

In Python, you can define functions inside other functions. These inner functions are known as nested functions or local functions. They are defined within the scope of the outer function and can only be accessed from within the outer function.

Syntax

def outer_function():
# outer function body
def inner_function():
    # inner function body
# calling the inner function
inner_function()

Example

  • Python

Python

def calculate_area(length, width):

def calculate_square_area():

return length * length

def calculate_rectangle_area():

   return length * width

if length == width:

   area = calculate_square_area()

else:

   area = calculate_rectangle_area()

return area

result1 = calculate_area(5, 5)

print(result1)  # Output: 25

result2 = calculate_area(4, 6)

print(result2) 


Output

24


In this example, we have an outer function called "calculate_area" that takes two parameters: "length" and "width". Inside the outer function, we define two inner functions: "calculate_square_area" and "calculate_rectangle_area". These inner functions calculate the area of a square and a rectangle, respectively.

The outer function checks if the length and width are equal. If they are, it calls the "calculate_square_area" function to calculate the area of a square. Otherwise, it calls the "calculate_rectangle_area" function to calculate the area of a rectangle. Finally, the outer function returns the calculated area.

We can call the "calculate_area" function with different values for length and width, and it will automatically call the appropriate inner function based on the condition.

Inner functions have access to variables defined in the outer function's scope, but the outer function cannot access variables defined inside the inner functions.

Anonymous Functions in Python (Lambda Functions):

Python provides a way to create small, one-line functions without giving them a name. These functions are called anonymous functions or lambda functions. Lambda functions are defined using the "lambda" keyword and can be used wherever function objects are required.

Syntax

lambda arguments: expression

 

  • The "lambda" keyword is used to define an anonymous function.
     
  • "arguments" are the input parameters of the function (optional).
     
  • "expression" is a single expression that is evaluated and returned as the result of the function.

Example 1

  • Python

Python

square = lambda x: x ** 2

result = square(5)

print(result)

  

Output

25


In this example, we define a lambda function that takes one argument "x" and returns the square of "x". We assign this lambda function to the variable "square". We can then call the lambda function using the variable name and pass an argument to it. In this case, we pass the value 5, and the lambda function returns its square, which is 25.

Example 2

  • Python

Python

add_numbers = lambda a, b: a + b

result = add_numbers(3, 4)

print(result) 

Output:

 7


In this example, we define a lambda function that takes two arguments "a" and "b" and returns their sum. We assign this lambda function to the variable "add_numbers". We can then call the lambda function using the variable name and pass two arguments to it. In this case, we pass the values 3 and 4, and the lambda function returns their sum, which is 7.

Lambda functions are often used in combination with built-in functions like map(), filter(), and reduce() to perform operations on iterables in a concise way.

Example 3

  • Python

Python

numbers = [1, 2, 3, 4, 5]

squared_numbers = list(map(lambda x: x ** 2, numbers))

print(squared_numbers) 


Output

 [1, 4, 9, 16, 25]


In this example, we have a list of numbers called "numbers". We use the map() function along with a lambda function to square each number in the list. The lambda function takes each number "x" and returns its square "x ** 2". The map() function applies the lambda function to each element of the "numbers" list and returns an iterator. We convert the iterator to a list using the list() function and assign it to the variable "squared_numbers".

Lambda functions provide a concise way to define small, anonymous functions in Python. They are useful when you need to pass a simple function as an argument to another function or when you want to perform a quick operation without defining a named function.

Recursive Functions in Python

Recursive functions are functions that call themselves within their own definition. They solve problems by breaking them down into smaller subproblems until a base case is reached. Recursive functions are useful for solving problems that can be divided into smaller, similar subproblems.

Syntax

def recursive_function(parameters):
if base_case:
# base case logic
return result
else:
# recursive case logic
recursive_function(modified_parameters)


The function is defined with a name and parameters.

The base case is a condition that determines when the recursion should stop. It is typically a simple case that can be solved directly without further recursion.

If the base case is not met, the recursive case is executed, where the function calls itself with modified parameters.

Example 1 (Factorial)

  • Python

Python

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

result = factorial(5)

print(result) 


Output

120


In this example, we define a recursive function called "factorial" that calculates the factorial of a given number "n". The factorial of a non-negative integer "n" is the product of all positive integers from 1 to "n".

The base case is when "n" is equal to 0. In this case, the factorial of 0 is defined as 1, so we return 1.

If "n" is not equal to 0, we enter the recursive case. We return the product of "n" and the factorial of "n - 1". This recursive call progressively reduces the value of "n" until it reaches the base case.

When we call the "factorial" function with an argument of 5, it recursively computes the factorial of 5 by breaking it down into smaller subproblems: 5 * factorial(4), 4 * factorial(3), 3 * factorial(2), 2 * factorial(1), and finally 1 * factorial(0), which returns 1. The final result is 120.

Example 2 (Fibonacci Sequence):

  • Python

Python

def fibonacci(n):

if n <= 1:

return n

else:

return fibonacci(n - 1) + fibonacci(n - 2)

result = fibonacci(6)

print(result) 


Output

8


In this example, we define a recursive function called "fibonacci" that calculates the nth number in the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.

The base cases are when "n" is less than or equal to 1. If "n" is 0, we return 0, and if "n" is 1, we return 1.

If "n" is greater than 1, we enter the recursive case. We return the sum of the previous two Fibonacci numbers by recursively calling the "fibonacci" function with "n - 1" and "n - 2".

When we call the "fibonacci" function with an argument of 6, it recursively computes the 6th Fibonacci number by breaking it down into smaller subproblems: fibonacci(5) + fibonacci(4), fibonacci(4) + fibonacci(3), fibonacci(3) + fibonacci(2), fibonacci(2) + fibonacci(1), fibonacci(1) + fibonacci(0), and finally returning the sum of the base cases. The final result is 8.

Recursive functions can be powerful for solving certain problems, but they should be used carefully to avoid excessive recursion depth and potential stack overflow errors.

Return Statement in Python Function:

The return statement in Python is used to exit a function and optionally pass a value back to the caller. It allows a function to compute a result and send it back to the point where the function was called.

Syntax

def function_name(parameters):
# function body
return value

 

  • The "return" keyword is used to specify the value that the function should return.
     
  • The "value" can be a single value, an expression, or even multiple values separated by commas.
     
  • When the return statement is encountered, the function immediately exits, and the specified value is returned to the caller.

Example 1

  • Python

Python

def square(x):

return x ** 2

result = square(5)

print(result) 


Output:

 25


In this example, we define a function called "square" that takes a parameter "x". Inside the function, we use the return statement to return the square of "x", which is calculated as "x ** 2".

When we call the "square" function with an argument of 5, it computes the square of 5 and returns the value 25. The returned value is then assigned to the variable "result", which we print.

Example 2

  • Python

Python

def get_name():

name = input("Enter your name: ")

return name

def greet(name):

print("Hello, " + name + "!")

name = get_name()

greet(name)


In this example, we have two functions: "get_name" and "greet". The "get_name" function prompts the user to enter their name using the input() function and returns the entered name using the return statement.

The "greet" function takes a parameter "name" and prints a greeting message using the provided name.

We first call the "get_name" function, which prompts the user to enter their name and returns the entered name. We assign the returned value to the variable "name".

Then, we call the "greet" function and pass the "name" variable as an argument. The "greet" function prints the greeting message using the provided name.

Example 

output:

Enter your name: Mehak
Hello, Mehak!


The return statement is optional in a function. If a function does not have a return statement or if the return statement is used without a value, the function will implicitly return None.

Example 3:

  • Python

Python

def print_message(message):

print(message)

result = print_message("Hello, world!")

print(result) 


Output: 

None


In this example, the "print_message" function takes a parameter "message" and prints it using the print() function. However, there is no explicit return statement in the function.

When we call the "print_message" function with the argument "Hello, world!", it prints the message but does not return any value. The variable "result" is assigned the default return value of None.

The return statement is crucial for retrieving computed values from functions and allows you to use the returned values in further operations or assignments.

Pass by Reference and Pass by Value in Python:

In Python, the behavior of passing arguments to functions is often described as "pass by reference" or "pass by value". However, the actual behavior is slightly more distinct and is sometimes referred to as "pass by assignment" or "call by object reference". Let's discuss how Python handles function arguments.

Pass by Reference

In Python, when you pass a mutable object (e.g., a list, dictionary, or custom object) as an argument to a function, the function receives a reference to the original object. This means that any modifications made to the object inside the function will affect the original object.

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]


In this example, we pass the list "numbers" to the "modify_list" function. Inside the function, we append the value 4 to the list using the append() method. This modification affects the original list, and the changes are visible both inside and outside the function.

Pass by Value

When you pass an immutable object (e.g., numbers, strings, or tuples) as an argument to a function, the function receives a copy of the value. Any modifications made to the parameter inside the function do not affect the original object.

Example:

  • Python

Python

def modify_number(x):

x = 10

print("Inside the function:", x)

num = 5

modify_number(num)

print("Outside the function:", num)


Output

Inside the function: 10
Outside the function: 5


In this example, we pass the integer value "num" to the "modify_number" function. Inside the function, we assign a new value (10) to the parameter "x". However, this assignment does not affect the original value of "num" outside the function.

It's important to note that even though immutable objects are passed by value, if you assign a new object to the parameter inside the function, it will not affect the original object.

Example:

  • Python

Python

def modify_string(s):

s = "Modified string"

print("Inside the function:", s)

message = "Hello"

modify_string(message)

print("Outside the function:", message)


Output

Inside the function: Modified string
Outside the function: Hello


In this example, we pass the string "message" to the "modify_string" function. Inside the function, we assign a new string value to the parameter "s". However, this assignment does not affect the original string "message" outside the function.

In Python, the behavior is actually a combination of pass by reference and pass by value, depending on the mutability of the object being passed. Mutable objects are passed by reference, allowing modifications to affect the original object, while immutable objects are passed by value, creating a new copy of the value inside the function.

Frequently Asked Questions

What is the difference between a parameter and an argument in Python functions?

A parameter is the variable defined in the function declaration, while an argument is the actual value passed to the function when it is called.

Can a Python function return multiple values?

Yes, a Python function can return multiple values by separating them with commas in the return statement. The values are returned as a tuple.

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

If a function doesn't have a return statement or if the return statement is used without a value, the function will implicitly return None.

Conclusion

In this article, we explained the concept of functions in Python. We learned how to define and call functions, work with parameters and arguments, and utilize different types of arguments such as default, keyword, positional, and arbitrary arguments. We also discussed recursive functions, lambda functions, and the return statement. 

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