零基础入门学习Python(10):函数
简单的函数介绍
>>> def myFirstFunc(): #不带参数的简单函数
print('这是我创建的第一个函数!')
>>> myFirstFunc() #函数调用
这是我创建的第一个函数!
>>> def mySecondFunc(name): #传入一个字符串name,name是形参
print("My name is " + name) #使用了字符串拼接
>>> mySecondFunc("Jessica") #"Jessics"是实参,调用带形参的函数时要写入实参
My name is Jessica
>>> def myThirdFunc(x,y): #带返回值的函数
"求两个数之和"
return (x+y)
>>> result = myThirdFunc(1,2) #可以把返回值赋给一个变量
>>> result
3
>>> myThirdFunc.__doc__ #可以查看函数中的文档
'求两个数之和'
函数参数有以下几种情况
1、关键字参数,即变量名
>>> def test1(pet,name):
print("The name of the " + pet+ " is " + name)
>>> test1("dog", "LittleSeven")
The name of the dog is LittleSeven
>>> test1("LittleSeven", "dog") #参数是按照关键字顺序传递的
The name of the LittleSeven is dog
>>> test1(name = "LittleSeven", pet = "dog") #可以写出形参名然后赋值
The name of the dog is LittleSeven
2、默认参数
>>> def test2(pet = "dog",name = "LittleSeven"):
print("The name of the " + pet+ " is " + name)
>>> test2() #有默认参数时,可以不写出参数直接调用
The name of the dog is LittleSeven
>>> test2("cat","maomi") #也可以直接传入实参,此时会覆盖默认参数
The name of the cat is maomi
3、收集参数:参数个数可变
>>> def test3(*params): #给形参变量名前加一个星号(*),即成为个数可变的形参
print("The length of parameter is: " , len(params))
print("The first argument is: " , params[0])
>>> test3(2,3,"Hello",3.14) #参数被打包成元组
The length of parameter is: 4
The first argument is: 2
>>> def test4(*params,addition): #有收集参数之后还可以有其他参数
print("The length of parameter is: " , len(params))
print("The additive value is: " , addition)
>>> test4(2,3,"Hello",3.14,addition = 7) #调用函数时,关键字参数必须写出形参名再赋值,否则会被当作收集参数的一员被打包到元组中
The length of parameter is: 4
The additive value is: 7
最后再介绍下函数的返回值,Python中函数可以返回多个值,默认是返回元组
>>> def back():
return (2,3.14,"Jessica") #以元组形式返回多个参数
>>> s = back()
>>> s
(2, 3.14, 'Jessica')