Can someone please explain to me in the code below. Why if we assign multiple variables (beans, jars, crates) to a single function(secret_formula(start_point)), each variable later has different value. I thought that if we assign in this way all variables will have the same value.So why this happens?
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(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")
CodePudding user response:
This has to be a dupe, but I couldn't find it in a cursory search..
If you assign to multiple variables, Python does not repeat the value. It instead looks at the right hand side of the assignment for a list of values, and assigns the elements of the list in order. It's just as if you did this:
a,b,c = 1,2,3
which assigns 1 to a
, 2 to b
, and 3 to c
. Inserting a function call doesn't change the semantics:
def foo():
return 1,2,3
a,b,c = foo() # same result
If you try to use it to assign the same value to multiple variables, you get an error:
a,b,c = 1
#=> TypeError: cannot unpack non-iterable int object
The only way to do that is to repeat the value on the right as many times as there are variables on the left, like this:
a,b,c = 1,1,1
or this:
a,b,c = [1]*3
CodePudding user response:
Your function secret_formula
returns 3 values, jelly_beans
, jars
, and crates
. You have the option of storing that all as one variable or unpacking it into three variables.
For example, one variable, but you access the values because the variable is a list:
all_values = secret_formula(start_point)
beans = all_values[0]
jars = all_values[1]
crates = all_values[2]
This is done faster and equivalently just by unpacking it with three variables, which is what your code example does.
beans, jars, crates = secret_formula(start_point)
CodePudding user response:
When in your function you return jelly_beans, jars, crates
, this creates a tuple containing those three independent values.
When calling that function and assigning it to beans, jars, crates
, you unpack each value from the returned tuple into three independent variables