不知道大家在学习Python的时候,有没有发现一个问题,函数里边的变量和脚本里边的变量好像是无关的。本文今天要讲的就是Python中的函数与变量,如果大家对于这个方面的内容有困惑,不妨来一起学习一下这个Python的基础内容。

python def函数 变量太多 python函数中的变量_python def函数 变量太多


首先大家先来看一看这个代码演示,理解下Python中的函数与变量的关系:

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)

通过这个案例,我们可以发现函数 cheese_and_crackers 传递很多的参数,然后在函数里把它们打印出来。我们可以在函数里用变量名,可以在函数里做运算,甚至可以将变量和运算结合起来。从一方面来说,函数的参数和我们的生成变量时用的 = 赋值符类似。事实上,如果你可以用 = 给一个东西命名,你也就可以将其作为参数传递给一个函数。

下面我们再来看看刚刚编写的代码的终端输出结果:

$ python ex19.py
We can just give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket.

OR, we can use variables from our script:
You have 10 cheeses!
You have 50 boxes of crackers!
Man that's enough for a party!
Get a blanket.

We can even do math inside too:
You have 30 cheeses!
You have 11 boxes of crackers!
Man that's enough for a party!
Get a blanket.

And we can combine the two, variables and math:
You have 110 cheeses!
You have 1050 boxes of crackers!
Man that's enough for a party!
Get a blanket.

通过上面的例子,我们已经认识了Python中的函数与变量。总的来讲,调用一个函数的方法可以很多,就看你如何发挥自己的想象力和创造力了~

好了,今天的分享就到这里