Can a function have multiple return statements?

0146

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_number function has three return statements.
  • Depending on the value of num, it will return "Positive", "Negative", or "Zero".
  • The function exits as soon as a return statement 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!

0 Comments

no data
Be the first to share your comment!