ex19函数和变量

#coding=utf-8
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"

print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)

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)

print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)

print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

从代码上看,这节课讲解了函数参数的几种表达方法,也就是函数的调用方法,需要注意的几个小问题:

  • amount_of_cheese和amount_of_crackers这两个变量会不会改变函数中的变量?
    不会,这些变量是在函数之外的,当它他们被传递到函数中以后,函数会为这些变量创建一些临时的版本,当函数运行结束后,这些临时变量就会被丢弃了,一切又回到了之前,但尽量不要让全局变量与函数中的变量重名。

你可能感兴趣的:(ex19函数和变量)