Yes, a function in Python can have multiple return statements. This allows the function to exit and return different values based on certain conditions.
Example:
def check_number(num):
if num > 0:
return "Positive"
elif num < 0:
return "Negative"
else:
return "Zero"
result = check_number(5) # result will be "Positive"
print(result)
Explanation:
- In this example, the
check_numberfunction has threereturnstatements. - Depending on the value of
num, it will return "Positive", "Negative", or "Zero". - The function exits as soon as a
returnstatement is executed, so only one of the return values will be used for any given function call.
Use Cases:
- Multiple return statements are useful for handling different conditions or outcomes within a function.
If you have more questions or need further examples, feel free to ask!
