Python return function

We can return the result or output from the function using a 'return' statement in the body of the function. For example,

return c #returns c value out of function

return 100 #returns 100

return lst #return the list that contains values

return x, y, c #returns 3 values

return function examples:

A Python program to find the sum of two numbers and return the result from the function.

CopiedCopy Code

def sum(a, b): 
   c = a+b
   return c
x = sum(10, 15) 
print('The sum is:', x) 
y = sum(1.5, 10.75) 
print('The sum is:', y)

A function to test whether a number is even or odd.

CopiedCopy Code

def even_odd(num): 
   if num% 2 == 0: 
print(num," is even") 
   else: 
print(num," is odd") 
even_odd(12) 
even_odd(13)

A Python program to calculate factorial values of numbers.

CopiedCopy Code

def fact(n): 
  prod=1 
  while n>=1: 
     prod*=n 
     n-=1 
  return prod
for i in range(1, 11): 
print('Factorial of {} is {}'.format(i, fact(i)))

Return multiple values from function

A function returns a single value in the programming languages like C or Java. But in Python, a function can return multiple values. When a function calculates multiple results and wants to return the results, we can use the return statement as:

return a, b, c

Here, three values which are in 'a', 'b' and 'c' are returned. These values are returned by the function as a tuple. Please remember a tuple is like a list that contains a group of elements. To grab these values, we can use three variables at the time of calling the function as:

x, y, z = function()

def sum_sub(a, b):

c = a + b

d = a - b

d = a - b

return c, d

A function that returns the results of addition, subtraction, multiplication and division.

CopiedCopy Code

def sum_sub_mul_div(a, b): 
   c = a + b 
   d = a - b 
   e = a * b 
   f = a/ b 
   return c, d, e, f 
t = sum_sub_mul_div(10, 5)
print('The results are:') 
for i in t: 
print(i, end='\t')

A function that returns the results of (a+b)2, (a-b)2, (a+b)3, (a-b)3.

CopiedCopy Code

def calc(a,b):
   w=(a+b)**2
   x=(a-b)**2
   y=(a+b)**3
   z=(a-b)**3
   return w,x,y,z
a=int(input("Enter value of 'a' : "))
b=int(input("Enter value of 'b' : "))
w,x,y,z=calc(a,b)
print("(a+b)^2 = :",w)
print("(a+b)^3 = :",y)
print("(a-b)^2 = :",x)
print("(a-b)^3 = :",z)