Home > Backend Development > Python Tutorial > Why Do Python Functions Without an Explicit `return` Statement Return `None`?

Why Do Python Functions Without an Explicit `return` Statement Return `None`?

DDD
Release: 2024-12-09 02:33:10
Original
947 people have browsed it

Why Do Python Functions Without an Explicit `return` Statement Return `None`?

Why Does Function Without Return Explicitly Return 'None'?

You have defined a function named lyrics() as shown below, expecting it to print a message.

def lyrics():
    print("The very first line")
print(lyrics())
Copy after login

However, instead of the expected output, you are encountering 'None' as a part of the output:

The very first line
None
Copy after login

The reason for this behavior lies in the nature of functions in Python. When a function doesn't explicitly return a value using the return statement, it implicitly returns None. This is because Python functions are objects, and they follow the convention of returning None if no explicit return value is provided.

To fix this issue, you need to use the return statement at the end of your lyrics() function to explicitly return the desired value. For instance, you could return the string "The very first line" as follows:

def lyrics():
    return "The very first line"

print(lyrics())
Copy after login

This modification will make the function explicitly return the desired string, resolving the 'None' output issue.

The above is the detailed content of Why Do Python Functions Without an Explicit `return` Statement Return `None`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template