简体   繁体   中英

Python Functions and Variables - Learn Python The Hard way ex19

Doesn't this function call variables from the script?, which goes against what Zed Shaw has stated...

I have put the comments in myself, my problem is this:

Zed Shaw states:

The variables in a function are not connected to variables in a script

But from what i see, the function is at the top with indentation, then when indentation starts its creating variables which are then linked to the function.

Doesn't this function call variables from the script?

I couldn't find a suitable answer: could someone elaborate on this bit of script and tell me if i am viewing it wrongly?

# This is the function with declared variables inside
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 thats enough for a party!"
    print "Get a Blanket. \n"

# This declares the amounts in the functions variables
print "We can just give the function numbers directly:"
cheese_and_crackers (20, 30)

# This variable sets the amounts
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
#This variable combines the two above and stores it in a single variable for the function to call
cheese_and_crackers(amount_of_cheese, amount_of_crackers)

# This uses the function, but has predefined variables with maths
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
#This combines variables with maths
print "And we can combine the two, variables and math:"
cheese_and_crackers (amount_of_cheese + 100, amount_of_crackers + 1000)

The variables are not at any time connected to the function parameters other than the fact that they are passed as arguments to the function. Calling foo(bar) doesn't connect bar to foo() , it merely passes the value of bar as the first parameter of the function. If that parameter also happens to be called "bar" then that is coincidence.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM