Python return Keyword/Statement

The return keyword in Python is used when we need to exit from a function with or without a returning value. For example:

def codes():
    print("First 'print()' inside 'codes()' function")
    print("Second 'print()' inside 'codes()' function")

def cracker():
    return 10

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

x = cracker()
x = codescracker(10, 50)

The output is:

First 'print()' inside 'codes()' function

In above program, the following statement:

print("Second 'print()' inside 'codes()' function")

is not executed, because just before this statement, a return statement or keyword is used. Therefore the program flow exists from this function.

Note - After the return statement, remaining statement(s) will be not executed, if available, inside the same function.

Python return Keyword or Statement Example

The program given below is an example of return statement:

def add(x, y):
    return x+y

def square(x):
    return x*x

def great(x, y):
    if x>y:
        return x
        return y

print("1. Add Two Numbers")
print("2. Find Square of a Number")
print("3. Find Greatest of Two Numbers")

print("\nEnter Your Choice (1-3): ", end="")
choice = int(input())

if choice == 1 or choice == 3:
    print("\nEnter any two numbers: ", end="")
    a = int(input())
    b = int(input())

if choice == 1:
    print("\nResult =", add(a, b))

elif choice == 2:
    print("\nEnter a Number: ", end="")
    num = int(input())
    print("\nResult =", square(num))

elif choice == 3:
    print("\nGreatest =", great(a, b))

    print("\nInvalid Choice!")

The snapshot given below shows the sample run, with user input 3 as choice, 10 and 20 as two numbers:

python return keyword

Python Online Test

« Previous Tutorial Next Tutorial »

© Copyright 2021. All Rights Reserved.