Multiple returns in python in a function

Йосип Ыыы :

I'm currently trying to make a function where it returns multiple return outputs in a single function. I'll add an example of what I'm trying to achieve below.

def verify(self, isRound: bool = None, isColored: bool = None, isBounce: bool = None):
    if isRound:  # When 'isRound' is True
        return "Object is round"

    if not isRound:  # When 'isRound' is False
        return "Object is not round"
   
    if isColored:  # When 'isColored' is True
        return "Object is colored"

    if not isColored:  # When 'isColored' is False
        return "Object is not colored"
    
    if isBounce:  # When 'isBounce' is True
        return "Object bounces"

    if not isBounce:  # When 'isBounce' is False
        return "Object doesnt bounce"

Input: verify(isRound = True, isColored = False)

Output:

"Object is round"

"Object is not colored"

echefede :

When you return, the function returns control to the upper code. You better make a list and return it at the end.

def verify(self, isRound: bool = None, isColored: bool = None, isBounce: bool = None):

    res = []  # To return at end

    if isRound:  # When 'isRound' is True
        res.append("Object is round")

    if not isRound:  # When 'isRound' is False
        res.append("Object is not round")
   
    if isColored:  # When 'isColored' is True
        res.append("Object is colored")

    if not isColored:  # When 'isColored' is False
        res.append("Object is not colored")
    
    if isBounce:  # When 'isBounce' is True
        res.append("Object bounces")

    if not isBounce:  # When 'isBounce' is False
        res.append("Object doesnt bounce")

    return res

Also you can make it more readable with some changes:

def verify(self, isRound: bool = None, isColored: bool = None, isBounce: bool = None):

    res = []  # To return at end

    res.append("Object is round" if isRound else "Object is not round")
    res.append("Object is colored" if isColored else "Object is not colored")
    res.append("Object bounces" if isBounce else "Object doesnt bounce")

    return res

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related