学分高考 Python

Python中的函数与变量讲解

发布时间: 2022-05-25 19:18:01

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

函数与变量

首先大家先来看一看这个代码演示,理解下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中的函数与变量。总的来讲,调用一个函数的方法可以很多,就看你如何发挥自己的想象力和创造力了~

温馨提示:
本文【Python中的函数与变量讲解】由作者教培参考提供。该文观点仅代表作者本人,学分高考系信息发布平台,仅提供信息存储空间服务,若存在侵权问题,请及时联系管理员或作者进行删除。
我们采用的作品包括内容和图片部分来源于网络用户投稿,我们不确定投稿用户享有完全著作权,根据《信息网络传播权保护条例》,如果侵犯了您的权利,请联系我站将及时删除。
内容侵权、违法和不良信息举报
Copyright @ 2024 学分高考 All Rights Reserved 版权所有. 湘ICP备17021685号