Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python return Keyword



The Python return keyword is used when we define a function. It will return the value at the end of the function. The statements after the return will not be executed. It is a case-sensitive.

The return cannot be used outside the function. If the function, return statement is without any expression, then special value None is returned.

Syntax

Following is the syntax of the Python return keyword −

def function_name():
    statement1
    statement1
    
    return expression

Example

Following is a basic example of the Python return keyword −

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

var1 = 13
var2 = 10
result_1 = Sum(var1, var2)
print(result_1)

Output

Following is the output of the above code −

23

Using 'return' value in void Function

The function which does not perform any operations and the body of the function is empty is known as void function. To avoid IndentationError, we use pass keyword. The void function returns None.

Example

Here, we have created a void function and found the return type of it −

def Empty():
    pass

print("Return type of void function :",Empty())

Output

Following is the output of the above code −

Return type of void function : None

Using 'return' Keyword in class

The functions which are defined inside the class known as methods. In methods, we use return keyword to return any value or expression from the method

Example

Here, we have created a class, Tp and defined method, Python() returned a value −

class Tp:
    def Python(self):
        var1 = "Welcome To Python Tutorials"
        return var1

Obj1 = Tp()
print(Obj1.Python())

Output

Following is the output of the above code −

Welcome To Python Tutorials

Returning a Tuple

The function which returns more than one value at the same time, it will return in the form of tuple.

Example

Here, we have defined a function, Tup() and return two values at the same time −

def Tup():
    var1 = "Welcome to Tutorialspoint"
    var2 = len(var1)
    return var1, var2
    
print(Tup()) 

Output

Following is the output of the above code −

('Welcome to Tutorialspoint', 25)   

Returning a List

A function can also return list as its return value.

Example

Here, we have defined a function, num() and it returned list of even number below 10 −

def num(n):
    list1 = []
    for i in range(0,n):
        if i%2==0:
            list1.append(i)
    
    return list1

n= 10
result_1 = num(n)
print("List of even numbers below",n,":", result_1)

Output

Following is the output of the above code −

List of even numbers below 10 : [0, 2, 4, 6, 8]
python_keywords.htm
Advertisements