Home > Backend Development > Python Tutorial > Why Does My Python `print` Statement Output 'None'?

Why Does My Python `print` Statement Output 'None'?

Patricia Arquette
Release: 2024-12-18 05:02:13
Original
748 people have browsed it

Why Does My Python `print` Statement Output

Why the Output Prints None"

In Python, the "print" statement can be used to display information in the output console. However, if there are multiple "print" statements within a program, their effects can be unexpected.

Consider the following code:

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

print(lyrics())
Copy after login

In this code, there are two "print" statements: one inside the "lyrics" function and another outside the function. When a function doesn't explicitly return a value, it implicitly returns None.

When the "lyrics" function is called with the "print(...)" statement, it executes and prints "The very first line" to the output console. However, since the function doesn't return a value, it implicitly returns None. This None value is then passed to the second "print(...)" statement outside the function, which prints it to the console.

As a result, the output contains both "The very first line" and "None". To avoid this issue, you should use a "return" statement at the end of the function to return a specific value. For example:

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

print(lyrics())
Copy after login

In this case, the "lyrics" function explicitly returns the string "The very first line", which is then printed by the second "print(...)" statement outside the function. This results in a clear output of "The very first line" without the unnecessary "None" value.

The above is the detailed content of Why Does My Python `print` Statement Output '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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template