• 在线客服

  • 扫描二维码
    下载博学谷APP

  • 扫描二维码
    关注博学谷微信公众号

  • 意见反馈

原创 Python中的函数与变量讲解

发布时间:2020-04-29 09:46:23 浏览 4121 来源:博学谷 作者:照照

    不知道大家在学习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基础学习笔记之运算符 下一篇: Python基础学习之布尔表达式

相关推荐 更多

热门文章

  • 前端是什么
  • 前端开发的工作职责
  • 前端开发需要会什么?先掌握这三大核心关键技术
  • 前端开发的工作方向有哪些?
  • 简历加分-4步写出HR想要的简历
  • 程序员如何突击面试?两大招带你拿下面试官
  • 程序员面试技巧
  • 架构师的厉害之处竟然是这……
  • 架构师书籍推荐
  • 懂了这些,才能成为架构师
  • 查看更多

扫描二维码,了解更多信息

博学谷二维码