Skip to content

Python function return nothing

  • by

There is no such thing as “returning nothing” in the Python function. If no explicit return statement is used, Python treats it as returning None.

def f(x):
    if x>1:
       return(x)
    else:
        # don't return anything

To return ‘nothing’ use pass, which returns the value None if put in a function(Functions must return a value, so why not ‘nothing’). You can do this explicitly and return None yourself though.

Python function returns nothing

Simple example code.

def f(x):
    if x > 1:
        return x
    else:
        pass


print(f(0))

or

def f(x):
    if x > 1:
        return x
    else:
        print("Function Return literally nothing")
        None


print(f(0))

Output:

Python function returns nothing

Python Function Return None Without Return Statement

The function does not have a return statement. The function in that case implicitly returns None.

def func():
    pass


print(func())

Output: None

Here’s an example showing different scenarios where a function might return None:

def example_function_1():
    pass  # No return statement

def example_function_2():
    return None  # Explicitly returns None

def example_function_3(condition):
    if condition:
        return "Condition met"
    # No return statement if condition is False

def example_function_4(value):
    if value > 10:
        return "Greater than 10"
    # No return statement if value is 10 or less

result1 = example_function_1()  # result1 will be None
result2 = example_function_2()  # result2 will be None
result3 = example_function_3(False)  # result3 will be None
result4 = example_function_4(5)  # result4 will be None

print(result1)  # Output: None
print(result2)  # Output: None
print(result3)  # Output: None
print(result4)  # Output: None

In each of these examples, the functions return None for different reasons.

Comment if you have any doubts or suggestions on this Python return topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading