How to return a value from a function?

前端 未结 5 1108
Happy的楠姐
Happy的楠姐 2021-01-28 21:39

Yes, I\'ve read tons of examples on this but I still don\'t get it.

I\'m learning Python and I made this script in order to help me understand how to \'return\':

5条回答
  •  情书的邮戳
    2021-01-28 22:11

    In calc_pay_rise, you are throwing away the value returned by the random_number() call; instead, do randmom = random_number(). What you've misunderstood is how variables work—local variables in one function (e.g. def random_number) are not visible in other functions (e.g. def calc_pay_rise).

    def random_number():
        random = 0  # not sure what's the point of this
        return (random + 5) * 10
    
    def calc_pay_rise():
        return 5 + random_number()
    
    calc_pay_rise()
    

    I've also reduced the code by eliminated all the stuff that does nothing.

    P.S. if the code is really reduced to the absolute minimum, you're left with nothing, because in its current form, the code does absolutely nothing:

    def random_number():
        random = 0  # not sure what's the point of this
        return (random + 5) * 10
    # is the same as 
    def random_number():
        return 50
    

    and

    def calc_pay_rise():
        return 5 + random_number()
    # is the same as
    def calc_pay_rise():
        return 5 + 50  # because random_number always returns 50
    

    and

    calc_pay_rise()
    # is really just the same as writing
    5 + 50
    # so you're not doing anything at all with that value, so you might as well eliminate the call, because it has no side effects either.
    

提交回复
热议问题