Home >Backend Development >Python Tutorial >Why Does Python\'s `print()` Function Return `None`?

Why Does Python\'s `print()` Function Return `None`?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 09:59:12430browse

Why Does Python's `print()` Function Return `None`?

Why Does the Print Function Return None?

In Python, the print() function is commonly used to display output on the console. However, one perplexing behavior of print() is its ability to return None. This can lead to confusion, especially when dealing with code that utilizes both printing and variable assignment.

Within the example code, the following occurs:

a = print(print("Python"))

The print() function is called twice, resulting in output as well as variable assignment. The first print() displays "Python" on the console. The second print() call, which is assigned to variable a, returns None. This unexpected behavior stems from the fact that print() does not return the printed value but rather None.

print(type(a))

When the type of a is checked using type(), it is classified as a 'NoneType' object. This confirms that the variable a does not hold the printed value but rather None.

To further clarify, consider the following example:

a = print("hey")

While "hey" is successfully printed on the console, inspecting the variable a using type() reveals that it is a 'NoneType' object.

It is important to distinguish between printing and returning. print() is used to display output while return is utilized to provide a return value from a function or expression. Although the outcomes of printing and returning may appear similar in the context of the Python interpreter, they are fundamentally different. print()'s focus lies in outputting data, whereas return is concerned with providing a value as a result of computation.

In summary, the print() function in Python does not return the printed value. Instead, it returns None, which can result in unexpected behavior if not understood correctly. It is crucial to differentiate between printing and returning to avoid confusion when working with Python code.

The above is the detailed content of Why Does Python\'s `print()` Function Return `None`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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