Arguments and Return in Python Functions
In Python, we often want to give some input values to a function and also get an output back. The values we give are called arguments and the output we get is called a return value.
This makes our code reusable and easy to manage. A function in Python can:
- Take zero, one or many arguments
- Return a value back to where it was called
Parameters vs Arguments
Many times, people mix up these two words. But they are slightly different.
| Parameter | Argument |
|---|---|
| Variable names given in the function definition. | Actual values given in the function call. |
| Works like a placeholder inside the function. | These values get copied to the parameters. |
Example: def add(a, b):here a & b are
parameters. |
Example: add(5, 3)here 5 & 3 are
arguments.
|
What are Arguments?
Arguments are the values we pass to a function when we call it. These values go into the parameters of the function.
Syntax:
def function_name(parameter1, parameter2):
# code using the parameters
...
function_name(value1, value2)
Example 1: Function with arguments but no return
def greet(name):
print("Hello,", name)
greet("Devanshi")
Output:
Hello, Devanshi
Explanation:
nameis a parameter in the function definition."Devanshi"is an argument passed during the function call.- This function does not return anything, it only prints.
What is Return?
The return statement is used to send a value back from the function to
where it was called.
When Python sees return, it immediately exits the function.
Syntax with Return:
def function_name(parameters):
# code
return value
result = function_name(arguments)
print(result)
Note: The returned value can be stored in a variable or used directly.
Example 2: Function with arguments and return value
def add(a, b):
return a + b
result = add(4, 6)
print("Sum is:", result)
Output:
Sum is: 10
Explanation:
aandbare parameters.4and6are arguments given at the time of calling.return a + bsends back the result which gets stored inresult.
Example 3: Function returning a string
def message(name):
return "Welcome, " + name
print(message("Student"))
Output:
Welcome, Student
Explanation:
- This function takes
nameas a parameter. - Returns a greeting string using the argument passed.
- We directly print the returned value.
Summary:
- Parameters: Names used inside the function definition to receive values.
- Arguments: Actual values we send to the function when calling it.
- Return: Used to send a result back to the caller.
- Functions can have parameters, return values, both, or neither.
returnends the function and sends the output immediately.