我不明白beans, jars, crates = secret_formula(start_point)
为什么会引用jelly_beans, jars, crates
。
这是来自Learn python的Ex24艰难之路。下面我将从Stackoverflow问题中得到几乎相同答案的答案,但没有完全解释它,所以我真的掌握了它。
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)
这是我在其他地方找到的答案:
Learn Python the Hard Way - Exercise 24
由于Python的作用域规则,名称jelly_beans仅在secret_formula函数内有效。这就是你不能通过函数之外的print jelly_beans之类的语句引用它的原因。 请注意,secret_formula将一个元组返回给其调用者。因此,当您键入:beans,jars,crates = secret_formula(start_point)时,您指定对secret_formula(具有特定参数)的调用,并将元组的内容分配给三个不同的名称。
我明白我们通过乘以已开始* 1000来达到50000。
但是,为什么我们会在以下地址得到答案:
print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)
答案 0 :(得分:3)
为什么我们不能称豆豆冻豆?为什么我们可以用罐子和板条箱?
事实并非如此。你可以随意调用你的变量,甚至是jelly_beans。
<MenuItem Header="Edit">
<MenuItem Header="Copy" Name="MenuCopy"
Command="Copy"></MenuItem>
<MenuItem Header="Paste" Name="MenuPaste"
Command="Paste"></MenuItem>
</MenuItem>
但请记住,这些变量与函数内部的变量无关。
最好的学习方法就是去做。