So I wrote this function from a book I am reading, and this is how it starts:
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
ok, makes sense. and then, this is when this function is run where I got a little confused and wanted to confirm something:
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
the thing that confused me here is that the amount_of_cheese and amount_of_crackers is changing the variables (verbage? not sure if i am saying the right lingo) from cheese_count and boxes_of_crackers repectively from the first inital variable labels in the function.
so my question is, when you are using a different variable from the one that is used in the initial function you wrote, why would you change the name of the AFTER you wrote out the new variable names? how would the program know what the new variables are if it is shown after it?
i thought python reads programs top to bottom, or does it do it bottom to top?
does that make sense? i’m not sure how to explain it. thank you for any help. 🙂
(python 2.7)
I think you are just a bit confused on the naming rules for parameter passing.
Consider:
and you can call
fooas follows:and you’ll see:
The variable names of the arguments (
a, b) in the function signature (1st line of function definition) do not have to agree with the actual variable names used when you invoke the function.Think of it as this, when you call:
It’s saying: “invoke the function
foo; passxin asa, passyin asb“. Furthermore, the arguments here are passed in as copies, so if you were to modify them inside the function, it won’t change the values outside of the function, from where it was invoked. Consider the following:and you’ll see: