艰苦学习Python - 练习24

时间:2015-05-11 10:03:01

标签: python function python-2.7

described here的额外信用问题:

  

问:为什么要调用变量jelly_beans,但名称为beans   以后?

     

答:这是功能如何运作的一部分。请记住里面的   函数变量是临时的。当你返回它然后它可以   分配给变量以供日后使用。我只是创建了一个名为的新变量   beans保留返回值。

“函数内部的变量是暂时的”是什么意思?这是否意味着变量在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)

1 个答案:

答案 0 :(得分:6)

  

这是否意味着变量在return

之后无效

是;当函数结束时,所有本地作用域的名称(在您的示例中为jelly_beans)都不再存在。名称jelly_beans只能在secret_formula内访问。

  

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

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

  

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

仅删除函数内的本地名称,不一定是它们引用的对象。当您return jelly_beans, jars, crates时,会将对象(而不是名称)传递回任何名为secret_formula的内容。您可以在函数外部为对象指定相同的名称或完全不同的对象:

foo, bar, baz = secret_formula(...)

This article是有关如何在Python中使用命名的有用介绍。