Python教程 |
您所在的位置:网站首页 › python中函数返回值怎么理解 › Python教程 |
什么是函数?
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。 函数能提高应用的模块性,和代码的重复利用率。 如何定义函数? 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ()任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。函数内容以冒号起始,并且缩进。return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。 函数语法: def 函数名(参数列表): 函数体 无参实例:无参也就是def()括号里面没有参数的,这种是最简单的函数块,直接调用就可以 def hello(): print("这里是def函数块") hello()现在来点复杂一点的,我们往函数的括号传入两个参数计算结果试试看 有参实例: def hello(num1,num2): result = num1+num2 print(result) hello(10,10)比如上面例子所说的 def hello(num1,num2) 这个例子,num1和num2是形参——完成其工作所需的事情,在调用hello(10,10)方法时传入的10是实参——调用函数时传递给函数的信息,实参会在被调用是传给形参 怎么多次调用函数只需调用hello函数即可,如: def hello(num1,num2): result = num1+num2 print(result) hello(10,10) hello(100,100)也可以使用关键字实参(键——值形式),但是有一个使用关键字实参另一个也要使用关键字实参,不然会报错 def hello(num1,num2): result = num1+num2 print(result) hello(num1=10,num2=10)返回值让你能够将程序的大部分繁重工作移到函数中去完成,从而简化主程序 实例: def get_result(num1,num2): result = num1+num2 return result #返回result结果 str_result = get_result(10,10) #定义一个str_result来接收一下get_result(10,10) print(str_result)打印为:20 任意传递实参有的时候我们在括号内定义几个参数就要传递几个参数,但是我们不想固定传入的参数要怎么做呢? def get_result(*function): return function result = get_result("one","two","three") print(result)形参名 *function中的星号让Python创建一个名为 function的空元组,并将收到的所有值都封装到这个元组中,不管传过来多少个值依然可以处理 多个关键字实参比如当我们不确定要传什么值的时候可以这样定义函数,如: def get_studentInfo(id,name,**student_info):实例 def get_studentInfo(id,name,**student_info): student = {} student['id'] = id student['name'] = name for key,value in student_info.items(): student[key] = value return student result = get_studentInfo(1,"lisa",student_class='class_one',student_age=18) print(result) |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |