Return a value from function

Introduction:

  • In Python, you can return a value from a function using the return keyword. 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 x with 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 add function:
    • The function takes two arguments, x and y.
    • The sum of x and y is stored in the variable result.
    • The function returns the value of result using the return statement.

Exercises:

  1. Return Product from multiply() Function:
    • Write a function multiply() that takes two arguments and returns their product.

      python
      def multiply(x, y):
          return x * y
      
      # Test the function
      print(multiply(4, 5))   
      • Output: 20
  2. Return Concatenated String from concatenate() Function:
    • Write a function concatenate() that takes two string arguments and returns their concatenated result.

      python
      def concatenate(str1, str2):
          return str1 + str2
      
      # Test the function
      print(concatenate("Hello, ", "World!"))  
      • Output: Hello, World!
  3. Return Boolean from is_even() Function:
    • Write a function is_even() that takes an integer and returns True if the number is even and False if it is odd.

      python
      def is_even(number):
          return number % 2 == 0
      
      # Test the function
      print(is_even(4))  
      print(is_even(5))  
      • Output: True
      • Output: False

Summary:

  • In this tutorial, we learned how to return a value from a function using the return keyword. 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!