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
Release: 2025-01-02 19:37:39
Original
891 people have browsed it

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"
Copy after login

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!

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