I don't understand why beans, jars, crates = secret_formula(start_point)
refers to jelly_beans, jars, crates
.
This is the Ex24 from Learn python the hard way. Below I will put a answer from a Stackoverflow question with almost the same answer but didn't explain it fully so I really have a grasp of it.
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)
This is the answer I found elsewhere:
Learn Python the Hard Way - Exercise 24
Due to the scoping rules of Python, the name jelly_beans is valid only inside the secret_formula function. That is the reason you can not refer to it via a statement like print jelly_beans outside the function. Notice that secret_formula returns a tuple to its caller. Therefore, when you type: beans, jars, crates = secret_formula(start_point) you specify a call to secret_formula (with a certain parameter), and assign the contents of the tuple to three different names.
Q: Why can't we call beans jelly_beans? Why can we with jars and crates?
I do understand that we get to 50000 by multiplying started * 1000.
However, why do we get that answer at:
print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)
Why can't we call beans jelly_beans? Why can we with jars and crates?
It is not true. you can call your variable whatever you want, even jelly_beans.
jelly_beans, jars, crates = secret_formula(10000)
but have it in mind that these variable have nothing to do with those inside your function.
BEST Way to learn is to do it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.