是的,我还没有读过很多这样的例子。在
我在学习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()?在
试试这个:
当你调用一个返回一个值(在这个例子中是一个随机数)的函数时,你应该对返回的值做一些事情。在
还要注意,在
^{pr2}$random_number()
中本地定义的变量random
不能从其他函数“看到”—除非您在本地声明一个新变量,但是它可以有任何您想要的名称。另一种说法是:你需要设置一个名为“random”的变量
因此,你的计算工资增长函数应该是:
在
calc_pay_rise
中,您将丢弃random_number()
调用返回的值;相反,请执行randmom = random_number()
。你所误解的是变量如何在一个函数中起作用局部变量(例如def random_number
)在其他函数中是不可见的(例如def calc_pay_rise
)。在我还消除了所有不起作用的代码。在
p.S.如果代码真的被缩减到绝对最小值,那么您就什么都没有了,因为在当前的形式中,代码完全不做任何事情:
^{pr2}$以及
以及
相关问题 更多 >
编程相关推荐