Return a value from function
Introduction:
- In Python, you can return a value from a function using the
returnkeyword. This is useful for getting the result of a calculation or process done inside the function back to the part of the program that called it.
Syntax:
python
def someFunction():
# some code
return x
- Replace
xwith the value you want to return.
Example: Returning Sum from add() Function:
- This example defines an
add()function that takes two arguments and returns their sum.
Python Program:
python
# Define function that returns the sum of two arguments
def add(x, y):
result = x + y
return result
# Take two values
a = 3.14
b = 1.23
# Call the add function
output = add(a, b)
print(f'Output : {output}')
Output: 4.37
- About the
addfunction:- The function takes two arguments,
xandy. - The sum of
xandyis stored in the variableresult. - The function returns the value of
resultusing thereturnstatement.
- The function takes two arguments,
Exercises:
- Return Product from multiply() Function:
Write a function
multiply()that takes two arguments and returns their product.pythondef multiply(x, y): return x * y # Test the function print(multiply(4, 5))- Output:
20
- Output:
- Return Concatenated String from concatenate() Function:
Write a function
concatenate()that takes two string arguments and returns their concatenated result.pythondef concatenate(str1, str2): return str1 + str2 # Test the function print(concatenate("Hello, ", "World!"))- Output:
Hello, World!
- Output:
- Return Boolean from is_even() Function:
Write a function
is_even()that takes an integer and returnsTrueif the number is even andFalseif it is odd.pythondef is_even(number): return number % 2 == 0 # Test the function print(is_even(4)) print(is_even(5))- Output:
True - Output:
False
- Output:
Summary:
- In this tutorial, we learned how to return a value from a function using the
returnkeyword. This allows you to get results from functions and use them elsewhere in your program. Practice writing functions with return values to become proficient in this essential programming concept!