Online Tutorials & Training Materials | STechies.com
Register Login

What is the Use of Return Statement in Python?

|| 0

What is the Use of Return Statement in Python?
Stechies

In Python we use “return” as a keyword, here we can use function with or without return statement. If any function is called with return statement it simply return the value and exit a function.

Return statement simply return the values as output whereas print() function simply print the value.

Example with Return Statement:

# Python 3 Code
# working on return statement

def addvalue(a, b):
 return a + b

c = addvalue(10, 34)
print(c)

Output:

44

Here we have created a function name addvalue() to add two value a & b, and return the value as output by using return statement.

Example without Return Statement:

# Python 3 Code
# Function without return statement

def addvalue(a, b):
# Print the value of a+b
 print(a + b)

addvalue(10, 34)

Output:

44

In the above given example we have used print function to print the output of the function.

As you can see in the above example print function returns nothing but print the value directly as output.

Python Return Multiple Values

A function can return only one value or object as output, but if you want to return multiple value than you can return the same with the help of list, dictionary and tuple.

All you need to do is convert your multiple output in to list (array), dictionary or tuple, and return them as single object.

Example:

# Python 3 Code
# Function return multiple value as list

def myfunction(a, b):
   # Print the value of a+b
   add = a + b
   sub = a - b
   return(add, sub)

# Take multiple value in list
multiv = myfunction(10, 34)

# Print values in list
print('Addition: ', multiv[0]);
print('Subtraction: ' , multiv[1]);

Output:

Addition: 44
Subtraction: -24

Return True, False & String

Example:

# Python 3 Code
# Function return Boolean True/False

def myfunction(a, b):
if(a > b):
   return True # Return True
elif(a == b):
   return 'A is Equal to B' # Return String
else:
   return False # Return False

# Check Boolean
print(myfunction(10, 34))
print(myfunction(10, 10))
print(myfunction(22, 11))

Output:

False
A is Equal to B
True

Difference between Return and Print Statement in Python

Return

Print()

Returns the value of function as output.

Print the value of function on terminal.

Output of function can be pass to other function.

Output can not pass to other function.

# Python 3 Code
# working on return statement

def addvalue(a, b):
return a + b

c = addvalue(10, 34)
print(c)

 

def addvalue(a, b):
# Print the value of a+b
print(a + b)

addvalue(10, 34)