艰苦学习Python - 练习24

Mor*_*Re' 2 python function python-2.7

本练习的额外信用问题:

问:为什么你 稍后调用变量jelly_beans但名字beans

答:这是功能如何运作的一部分.请记住,在函数内部,变量是临时的.当您返回它时,可以将其分配给变量以供日后使用.我只是创建一个名为beanshold的新变量 来保存返回值.

什么是"函数内部的变量是暂时的"是什么意思?这是否意味着该变量在return?之后无效?似乎在函数缩进之后,我无法打印函数部分中使用的变量.

从答案中可以看出"当你返回它时,它可以被分配给一个变量供以后使用".有人可以解释一下这句话吗?

print "Let's practice everything."
print 'You\'d need to know \'bout escape with \\ that do \n newlines and \t tabs.' 


poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""

print "-------------"
print poem
print "-------------" 


five = 10 - 2 + 3 - 6 
print "This should be five: %s" % five 

def secret_formula(started):
    jelly_beans = started * 500 
    jars = jelly_beans / 1000 
    crates = jars / 100 
    return jelly_beans, jars, crates 


start_point = 10000 
beans, jars, crates = secret_formula(start_point) 

print "With a starting point of : %d" % start_point 
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates) 

start_point = start_point / 10 

print "We can also do that this way:" 
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 6

这是否意味着该变量在return?之后无效?

是; 当函数结束时,所有本地范围的名称(jelly_beans在您的示例中)都不再存在.该名称jelly_beans只能在其中访问secret_formula.

似乎在函数缩进之后,我无法打印函数部分中使用的变量.

您无法通过函数名称从函数外部访问它们(因此既jelly_beans不能secret_formula.jelly_beans访问也不能访问该值).这实际上是一件好事,因为这意味着您可以内部逻辑封装在函数中,而不会将其暴露给程序的其余部分.

从答案中可以看出"当你返回它时,它可以被分配给一个变量供以后使用".

只删除函数内的本地名称,不一定是它们引用的对象.当你return jelly_beans, jars, crates,这将对象(而不是名称)传递回任何被调用的东西secret_formula.您可以在函数外部为对象指定相同的名称或完全不同的对象:

foo, bar, baz = secret_formula(...)
Run Code Online (Sandbox Code Playgroud)

本文是有关如何在Python中使用命名的有用介绍.