Return Statements

In the previous chapter, when we called input(), it would take the input from the user and return it us. We used to get the input by saving it in a variable. In general, the value that a function call evaluates to is called the return value of the function.

When creating a function using the def statement, you can specify what the return value should be with a return statement. In code, return statement consists of the following:

  1. The return keyword
  2. The expression or value that the function should return

When an expression is used with a return statement, the return value is what this expression evaluates to. We will do an example to make this more clear:

import random

def getData(answerNumber):
       if answerNumber == 1:
           return 'Successful'
       elif answerNumber == 2:
           return 'Partially successful'
       elif answerNumber == 3:
           return 'Failed'
       else:
           return 'Reply hazy try again'

r = random.randint(1, 4)
data = getAnswer(r)
print(data)

As you can see, we return the String based on the expressions.

What if we have nothing to return? There is a value called None, which represents the absence of a value. None is the only value of the NoneType data type.

>>> data = print('Hello')
Hello
>>> None == data
True

In the above code, we get a True because there is no return statement in the print() function.

NOTE: By default, Python adds return None to the end of any function definition with no return statement. This is similar to how a while or for loop implicitly ends with a continue statement. Also, if you use a return statement without a value (that is, just the return keyword by itself), then None is returned.

results matching ""

    No results matching ""