How to return multiple values in a function (Python)?

This question already has an answer here:

  • Replacements for switch statement in Python? 44 answers

  • Just use a if...else statement. I guess what you want is:

    def person_detail(Person):
        Age, Sex = Person
        if Age<16:
            return 3 if Sex else 2
        else:
            return Sex
    

    您可以使用多个if语句,if-else语句或字典:

    d = {(0, 0): 0, (0, 1): 1, (1, 0): 2, (1, 1): 3}
    
    def person_detail(Person):
        Age, Sex = Person
        return d[Age < 16, Sex]
    

    In my opinion, you should just use a "long" if/else as suggested by @miindlek to make the different outcomes of the function clear. Also, I would suggest not just to return Sex but to return 1 if Sex else 0 , again to make exactly clear what the function returns.

    But if you prefer to have a very short return line, you could also use a ternary statement like so:

    return Sex + 2 if Age < 16 else Sex
    

    Or even shorter (but not easier to understand):

    return (Age < 16) * 2 + Sex
    
    链接地址: http://www.djcxy.com/p/42772.html

    上一篇: 复杂的switch语句

    下一篇: 如何在函数中返回多个值(Python)?