Home >Backend Development >Python Tutorial >Why Does My Python Function Print 'None' After the Correct Output?

Why Does My Python Function Print 'None' After the Correct Output?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-02 19:37:39872browse

Why Does My Python Function Print

Why Function Outputs "None" After the Intended Result

Within your provided code snippet, the function smaller is designed to compare two numbers and print the smaller one. However, it yields an unexpected result of "None" being printed after the intended output (i.e., "2").

Understanding the Cause

This "None" output arises from the absence of an explicit return statement in the smaller function. In Python, functions implicitly return "None" when no return statement is specified.

The Expected Behavior

To rectify this, you need to explicitly return the comparison result within the function. Here's an updated version of the code:

def smaller(x, y):
    if x > y:
        return y  # Explicitly return the smaller value
    else:
        return x  # Explicitly return the smaller value

print(smaller(2, 3))  # Now, it will correctly print "2"

With the explicit return values, the function properly returns the smaller number, discarding the default "None" behavior.

The above is the detailed content of Why Does My Python Function Print 'None' After the Correct Output?. 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