Python Function Return NoneType

In the previous articles, you have seen various types of functions. Function either return a value or nothing. In this article, you will learn about functions that return a None. The None is the only value that belong to None Type.

Advertisements

When Python Functions Return None

There are a number of situations when a python function returns a None value. We have listed them here.

  • Functions purposely returns a None.
  • Functions that does not return anything and assigned to a variable.
  • Function that returns another function

Now, we will see an example of each of these cases.

Function That Returns a None

A function is created and does some calculation and returns None. Consider the following example to understand this.

def expression_1(num):
     if num > 100:
         return num + 100
     else:
         return None
result = expression_1(90)
print(result)

In the example above example, if the number is less than 100, the result will get a value of None. The output of the program is given below.

== RESTART:C:/PythonExercises/function_return_none.py ==
None
>>> 

Function Returns Nothing

There are functions that does not return anything and in such case, the function automatically returns a None. The following example multiply two numbers but does nothing more than that. When the function is printed as output, the value of the output is None.

Advertisements
def multiply(n1, n2):
    result = n1 * n2
print(multiply(4, 7))

The output of the function is None. See below.

== RESTART: C:/PythonExercises/function_no_return.py ===
None
>>> 

Function That Return Another Function

In this case, the function returns another function. The program cannot print another function, therefore, it is equal to None.

def printChar():
     return print("D")
result = printChar()
print(result)

The output of the program is given below.

= RESTART: C:/PythonExercises/Func_Ret_OtherFunc.py =
D
None
>>> 

The output above is interesting because it shows how the values are printed sequentially. First, the print("D") is executed and "D" is printed.The second print statement is executed after the function terminates. Therefore, the final output is None.

In the next article, we will discuss about advanced python functions.



Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.