Python return Keyword/Statement

return values in python 50% 590 return value in python 50% 590 return python 50% 5400 return function python 50% 3600 python tutorial pdf 10% 590 python return function 50% 3600 python return 48% 5400 python programming pdf 10% 720 python programming cheat sheet pdf 25% 20 python practice 20% 2900 python pdf 10% 1600 python how to program pdf 10% 720 python functions return 50% 3600 python functions practice problems 28% 20 python functions practice 30% 90

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")
    return
    print("Second 'print()' inside 'codes()' function")

def cracker():
    return 10

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

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

The output is:

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

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
    else:
        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))

else:
    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 »


Liked this post? Share it!