
Python 定义函数使用 def 关键字,一般格式如下:
- def 函数名(参数列表):
- 函数体
定义一个函数:给了函数一个名称,指定了函数里包含的参数,和代码块结构。
- # 定义函数
- def printme( str ):
- # 打印任何传入的字符串
- print (str)
- return
-
- # 调用函数
- printme("我要调用用户自定义函数!")
- printme("再次调用同一函数")
- def my_ad(x):
- if not isinstance(x,(int,float)):
- raise TypeError#抛出异常
- print("kk")
以下是调用函数时可使用的正式参数类型
必需参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。
调用 printme() 函数,你必须传入一个参数,不然会出现语法错误
- def printme( str ):
- "打印任何传入的字符串"
- print (str)
- return
-
- # 调用 printme 函数,不加参数会报错
- printme()
- #可写函数说明
- def printme( str ):
- "打印任何传入的字符串"
- print (str)
- return
-
- #调用printme函数
- printme( str = "菜鸟教程")
- def asd(a,b,*,c,d):#*后面的c,d必须以关键字的形式传参
- print(a)
- print(b)
-
- asd(1,2,c = 3,b = 4)
调用函数时,如果没有传递参数,则会使用默认参数。以下实例中如果没有传入 age 参数,则使用默认值
默认值只会执行一次
官方推荐:默认参数尽量使用不可变类型
- #可写函数说明
- def printinfo( name, age = 35 ):
- "打印任何传入的字符串"
- print ("名字: ", name)
- print ("年龄: ", age)
- return
-
- #调用printinfo函数
- printinfo( age=50, name="runoob" )
- print ("------------------------")
- printinfo( name="runoob" )
-
- 结果
- 名字: runoob
- 年龄: 50
- ------------------------
- 名字: runoob
- 年龄: 35
return [表达式] 语句用于退出函数,选择性地向调用方返回一个表达式。不带参数值的 return 语句返回 None。之前的例子都没有示范如何返回数值,以下实例演示了 return 语句的用法:
- # 可写函数说明
- def sum( arg1, arg2 ):
- # 返回2个参数的和."
- total = arg1 + arg2
- print ("函数内 : ", total)
- return total
-
- # 调用sum函数
- total = sum( 10, 20 )
- print ("函数外 : ", total)
-
-
- 结果
- 函数内 : 30
- 函数外 : 30
*函数:常见的 *args args变量指向一个tuple(元组)对象
自动接收未匹配的位置参数,到一个元组对象中
- def asd(a,*b):
- print(a)
- print(b)
-
- asd(123)
- 运行结果
- 123
- ()
-
- asd(11,12,13,14,15)
- 运行结果
- 11
- (12,13,14,15)
参数类型是字符串、列表、元组、集合、字典的时候,可以解包
传递实参时,可以根据序列类型的参数前面添加一个*
自动将序列中的元素以此作为参数传递
实例
- def asd(a,b,c):
- print(a)
- print(b)
- print(b)
-
- asd(*"123")
-
- 1
- 2
- 3
-
-
- asd(*[4,5,6])
-
- 4
- 5
- 6
- def asd(a,b,c):
- print(a)
- print(b)
- print(b)
- d = {
- "a" : "as"
- "b" : "18"
- "c" : "吃饭"
- }
- asd(*d)
-
- a
- b
- c
-
- asd(**d)
-
- a: as
- b: 18
- c: 吃饭
- def asd(a,*arge):
- print(a)
- print(args)
-
- asd(100,*(1,2,3))
函数作为一种代码封装,可以被其他程序调用,当然,也可以被函数内部代码调用。这种函数定义中调用函数自身的方式称为递归。
- #计算阶乘:根据用户输入的整数n,计算并输出n的阶乘值
- def fact(n):#计算阶乘
- if n == 1:
- return 1
- else:
- return n * fact(n-1)
-
- num = eval(input("请输入一个正整数: "))
- print(fact(num))