如何从函数返回值?

2024-10-04 05:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

是的,我还没有读过很多这样的例子。在

我在学习Python,为了帮助我理解如何“返回”:

def random_number():
    random = 0
    random = (random + 5) * 10
    return random

def calc_pay_rise():
    payrise = 5
    random_number()
    payrise = payrise + random
    print payrise

calc_pay_rise()

我预计产量为55。 相反,我得到了一个错误:“global name”random“is not defined”。我想我在random_number()函数中定义了random的含义。在

有没有办法将random的值传递给函数calc_pay_rise()?在


Tags: 函数namenumberreturndef错误calcrandom
3条回答

试试这个:

payrise = payrise + random_number()

当你调用一个返回一个值(在这个例子中是一个随机数)的函数时,你应该对返回的值做一些事情。在

还要注意,在random_number()中本地定义的变量random不能从其他函数“看到”—除非您在本地声明一个新变量,但是它可以有任何您想要的名称。另一种说法是:

^{pr2}$

你需要设置一个名为“random”的变量

因此,你的计算工资增长函数应该是:

def calc_pay_rise():
    payrise = 5
    random = random_number()
    payrise = payrise + random
    print payrise

calc_pay_rise中,您将丢弃random_number()调用返回的值;相反,请执行randmom = random_number()。你所误解的是变量如何在一个函数中起作用局部变量(例如def random_number)在其他函数中是不可见的(例如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()

我还消除了所有不起作用的代码。在

p.S.如果代码真的被缩减到绝对最小值,那么您就什么都没有了,因为在当前的形式中,代码完全不做任何事情:

^{pr2}$

以及

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

以及

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.

相关问题 更多 >