Home >Backend Development >Python Tutorial >Why Does My Python Function Print 'None' After the Correct Output?
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!