17 函数:Python的乐高积木
一、创建一个函数
>>> def MyFirstFunction(): print('这是我创建的第一个函数!') print('我表示很鸡冻....') print('在此,我要感谢TVB,感谢CCTV,感谢小甲鱼,感谢泉泉,感谢我对象...')
二、调用一个函数
>>> MyFirstFunction() 这是我创建的第一个函数! 我表示很鸡冻.... 在此,我要感谢TVB,感谢CCTV,感谢小甲鱼,感谢泉泉,感谢我对象...
三、函数的实现原理(运行机制):
调用函数是,Python会往上寻找,找到【def】创建和定义内容↓
【存在问题】如果只是单纯的定义函数,效率还不如 for while 高。故...
四、创建一个带参数的函数
例①:
>>> def MyFirstFunction(name): print(name + '我爱你')
>>> MyFirstFunction() Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> MyFirstFunction() TypeError: MyFirstFunction() missing 1 required positional argument: 'name' '''提示需要一个‘name’的参数'''
>>> def MyFirstFunction(name): print(name + '我爱你') >>> MyFirstFunction('金小川') 金小川我爱你
例②:
>>> def add(num1, num2): result = num1 + num2 print(result) >>> add(1, 2) 3
五、函数的返回值 __return()
以上个例子为例,改成:
>>> add(1, 2) 3 >>> def add(num1, num2): return(num1 + num2) >>> print(add(1, 2)) 3
18 函数:灵活即强大
一、形参(parameter)和实参(argument)
例:
>>> def MyFirstFunction(name): print(name + '我爱你') '''name为形参''' >>> MyFirstFunction('金小川') '''金小川 为实参''' 金小川我爱你
二、函数文档
>>> def MyFirstFunction(name): '函数定义过程中的name叫做形参' #因为Ta只是一个形式,表示占据一个参数位置 print('传递进来的【' + name + '】叫做实参,因为Ta是具体的参数值!') >>> MyFirstFunction('金小川') 传递进来的【金小川】叫做实参,因为Ta是具体的参数值! >>> MyFirstFunction.__doc__ '函数定义过程中的name叫做形参' >>> help(MyFirstFunction) Help on function MyFirstFunction in module __main__: MyFirstFunction(name) 函数定义过程中的name叫做形参
【拓展】关于函数文档,到底用什么导出?【help】 or 【__doc__】
>>> print.__doc__ "print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream." >>> help(print) Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
显然是 __help()
三、关键字参数
>>> def SaySome(name, words): print(name + '—>' + words) >>> SaySome('李旭冉', '爱金小川!!') 李旭冉—>爱金小川!!
【存在问题】如果不小心把顺序搞混了:
>>> SaySome( '爱金小川!!', '李旭冉') 爱金小川!!—>李旭冉
【问题】那这个结果就不是我们想要的。
【解决方法】关键字参数:>>> SaySome( words = '爱金小川!!', name = '李旭冉') 李旭冉—>爱金小川!!
四、默认参数
>>> def SaySome(name='李旭冉', words='爱金小川!!'): print(name + '—>' + words) >>> SaySome() 李旭冉—>爱金小川!!
【疑问】这里没有输入参数,使用的是默认值。那如果输入参数会怎么样?
>>> def SaySome(name='李旭冉', words='爱金小川!!'): print(name + '—>' + words) >>> SaySome('李旭冉', '爱李旭冉的男朋友') 李旭冉—>爱李旭冉的男朋友
作用:默认参数是在参数定义的过程中,为形参赋初值;当函数调用的时候,如果忘记传递参数,函数就会自动去找默认值
五、收集参数(可变参数)
__适用于当作者也搞不清楚函数到底有几个参数时。
此时只需要在参数面前加个星号即可。>>> def test(*params): print('参数的长度是:', len(params)) print('第二个参数是', params[1]) print('第三个参数是', params[2]) print('第...太累啦,不写啦') >>> test(1, 'lxr', 4.3, 'jxc', '523', 6.66, 4,17, 6.01) 参数的长度是: 9 第二个参数是 lxr 第三个参数是 4.3 第...太累啦,不写啦
【注意】如果定义函数时,除了收集参数,还有其他的参数,记得用关键字参数!!
否则:>>> def test(*params, exp): print('参数的长度是:', len(params), exp) print('第二个参数是', params[1]) >>> test(1, 'lxr', 4.3, 'jxc', '523', 4,17, 6.01) Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> test(1, 'lxr', 4.3, 'jxc', '523', 4,17, 6.01) TypeError: test() missing 1 required keyword-only argument: 'exp'
【原因分析】没用关键字参数,系统默认把元组中的所有数都分给了收集参数,
故其他参数(exp)无效。【解决方法①】关键字参数
>>> def test(*params, exp): print('参数的长度是:', len(params), exp) print('第二个参数是', params[1]) >>> test(1, 'lxr', 4.3, 'jxc', '523', 4,17, exp = 6.01) 参数的长度是: 7 6.01 第二个参数是 lxr
【解决方法②】默认参数
>>> def test(*params, exp = 6.01): print('参数的长度是:', len(params), exp) print('第二个参数是', params[1]) >>> test(1, 'lxr', 4.3, 'jxc', '523', 4,17) 参数的长度是: 7 6.01 第二个参数是 lxr
19 函数:我的地盘听我的
一、函数没有过程
>>> def hello(): print('hello chuan!') >>> temp = hello() hello chuan! >>> temp >>> type(temp) <class 'NoneType'>
【解释】hello()没有返回值,故访问【temp】时,没有返回值;即使没有用“return”给
【temp】返回值,【temp】也不是什么都没有,而是可以返回【None】
二、Python的返回值
>>> def back(): return[1.2, '钏', 521] >>> back() [1.2, '钏', 521] >>> >>> def back(): return 1.2, '钏', 521 >>> back() (1.2, '钏', 521)
【解释】返回值很灵活,可以是列表,也可以是元组。
三、局部变量(Local VAriable)和全局变量(Global Variable)
(一)局部变量(Local VAriable)
def discounts(price, rate): final_price = price * rate return final_price old_price = float(input('请输入原价:')) rate = float(input('请输入折扣率:')) new_price = discounts(old_price, rate) print('打折后的价格是:', new_price) ================================ 请输入原价:100 请输入折扣率:0.7 打折后的价格是: 70.0
【】正常运行
def discounts(price, rate): final_price = price * rate return final_price print('这里试图打印局部变量final_price的值:', final_price) old_price = float(input('请输入原价:')) rate = float(input('请输入折扣率:')) new_price = discounts(old_price, rate) print('打折后的价格是:', new_price) ================================ 请输入原价:100 请输入折扣率:0.7 打折后的价格是: 70.0 Traceback (most recent call last): File "C:/Users/86199/Desktop/小甲鱼c/111.py", line 9, in <module> print('这里试图打印局部变量final_price的值:', final_price) NameError: name 'final_price' is not defined
Traceback (most recent call last):
File "C:/Users/86199/Desktop/小甲鱼c/111.py", line 9, in <module>
print('这里试图打印局部变量final_price的值:', final_price)
NameError: name 'final_price' is not defined【解析】因为【final_price】是局部变量,只可以在他所在的部分起作用(final_price在定义函数范围内),出了他所在范围,则不存在该变量。
(二)全局变量(Global Variable)
【尝试】在函数内打印全局变量
def discounts(price, rate): final_price = price * rate print('这里试图打印全局变量odl_price的值:', old_price) return final_price old_price = float(input('请输入原价:')) rate = float(input('请输入折扣率:')) new_price = discounts(old_price, rate) print('打折后的价格是:', new_price) ================================ 请输入原价:100 请输入折扣率:0.7 这里试图打印全局变量odl_price的值: 100.0 打折后的价格是: 70.0
【结果】可以打印!!
【尝试】在函数内修改全局变量
def discounts(price, rate): final_price = price * rate # print('这里试图打印全局变量odl_price的值:', old_price) old_price = 50 print('①修改后old_price的值是:', old_price) return final_price old_price = float(input('请输入原价:')) rate = float(input('请输入折扣率:')) new_price = discounts(old_price, rate) print('②修改后old_price的值是:', old_price) print('打折后的价格是:', new_price) ================================ 请输入原价:100 请输入折扣率:0.7 ①修改后old_price的值是: 50 ②修改后old_price的值是: 100.0 打折后的价格是: 70.0
【问题】
1、old_price并没有因为函数内的修改而变化;
2、①成功修改了,但是②并没有成功修改。【解析】如果在函数内试图修改一个全局变量,那么Python就会在函数内创建一个同名局部
变量代替(shadowing)。二者同名,但互不影响。再举个例子:
>>> count = 5 >>> def MyFun(): count = 10 print(count) >>> MyFun() 10 >>> print(count) 5
【总结】
全局变量在全局都可以被访问到。但是在函数内部,只可以访问,不可以修改。