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
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:
Output
The sum of 5 & 7 is 12
We can also assign the arguments to variables before passing them into the function:
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
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`:
Output
Hello, Rahul!
We can also override the default value by passing in a second argument:
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
def student_info(name, age):
print(f"Name: {name}, Age: {age}")
We can call this function using keyword arguments like this:
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
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
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
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
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
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
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
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
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
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
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 Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.