在介绍Python的函数之前我们先来回顾一下,我们平常写代码是不是需要什么功能就写什么功能,但是到后面深入你会发现在写代码的过程中,有好多代码是重叠的,就是一个功能块在不同的地方都被使用,但是每次都得重新写一遍,这样就造成了写程序的效率问题,而Python中的函数就可以很好的解决这么一点。例如一个登陆代码快的代码,你比如刚登陆的时候需要验证用户名密码,你执行他事件比如购物、结算等逻辑的时候也需要做验证,那如果我们把这个验证的逻辑封装成一个函数,然后用到的地方,想怎么调就怎么调用,所以减少代码的重复性是函数的特性之一。
def test(x):
'The function definitions'
x =1
return x
******************************************************************
def:定义函数的关键字
test:函数名
():内可定义形参
'':文档描述(非必要,但是强烈建议为你的函数添加描述信息)
x =1:泛指代码块或程序处理逻辑
return:定义返回值 **编程语言中函数定义:函数是逻辑结构化和过程化的一种编程方法,函数式编程就是先定义一个数学函数,然后按照这个数学模型用编程语言去实现它。 #!/usr/bin/env python3
# _*_coding:utf-8_*_
# Author: Lucky.chen
# 常规码代码
a, b = 5, 8
c = a * b
print(c)
print('我是分割线'.center(30, '*'))
# 函数方法
def calc(x, y):
res = x * y
return res # 返回函数执行结果
c = calc(a, b) # 结果赋值给c变量
print(c) Result: 40
************我是分割线*************
40 这不是功能一样吗,看起来并没有什么卵用!!!嘿嘿!
形式参数,不是实际存在,是虚拟变量。在定义函数和函数体的时候使用形参,目的是在函数调用时接收实参(实参个数,类型应与实参一一对应)。 实参: 实际参数,调用函数时传给函数的参数,可以是常量,变量,表达式,函数,传给形参。
形参是虚拟的,不占用内存空间,形参变量只有在被调用时才分配内存单元,实参是一个变量,占用内存空间,数据传送单向,实参传给形参,不能形参传给实参。 实参就是函数执行的时候用户调用函数实际传输的参数简称为实参,实参又分为位置参数和关键参数。 def test(x, y): # x, y是形参
print('x is %d, y is %d' % (x, y))
calc_age = x * y
return calc_age
# 3在前,6在后 那么传给函数的形参就是按照位置 x = 3 , y = 6
print(test(3, 6))
print('我是分割线'.center(30, '*'))
# 如果调用的时候6在前,3在后,那么 x = 6, y = 3
print(test(6, 3)) 结果如下: x is 3, y is 6
18
************我是分割线*************
x is 6, y is 3
18 关键参数实例如下: def test(x, y, z): # x, y是形参
print('x is %d, y is %d, z is %d' % (x, y, z))
calc_age = x * y * z
return calc_age
# 指定y和z的值而x的值就是默认出入位置为第个的实参
print(test(3, y=2, z=3))
print('我是分割线'.center(30, '*'))
# 指定y和z的值,但是y和z的位置对调
print(test(3, z=2, y=3)) 结果如下: x is 3, y is 2, z is 3
18
************我是分割线*************
x is 3, y is 3, z is 2
18 如果这样呢? def test(x, y, z): # x, y是形参
print('x is %d, y is %d, z is %d' % (x, y, z))
calc_age = x * y * z
return calc_age
# 我指定第一个实参的数值,而不指定y和z的呢?
print(test(x=3, 2, 3)) 结果如下报错了: File '/Users/crh/PycharmProjects/app/test.py', line 12
print(test(x=3, 2, 3))
^
SyntaxError: positional argument follows keyword argument 如上实例介绍可以得出如下结论: def test(x, y=3, z): # x, y是形参
print('x is %d, y is %d, z is %d' % (x, y, z))
calc_age = x * y * z
return calc_age
# 只传两个参数,按照正常逻辑 x=1, y=3, z=3
print(test(1, 3))
# 但是报错了 报错如下: File '/Users/crh/PycharmProjects/app/test.py', line 6
def test(x, y=3, z): # x, y是形参
^
SyntaxError: non-default argument follows default argument def test(x, y, z=3): # x, y是形参
print('x is %d, y is %d, z is %d' % (x, y, z))
calc_age = x * y * z
return calc_age
# 只传两个参数,按照正常逻辑 x=1, y=3, z=3
print(test(1, 6)) 结果如下: x is 1, y is 6, z is 3
18 def test(x, z, y=3): # x, y是形参
print('x is %d, y is %d, z is %d' % (x, y, z))
calc_age = x * y * z
return calc_age
# 只传两个参数,按照正常逻辑 x=1, y=3, z=3
print(test(3, 2)) 结果如下: x is 3, y is 3, z is 2
18 如上实例可以知道,函数的形参设置默认参数的时候,默认参数应该放到非默认参数后面,否则按照位置参数传入则就会报错,除非传入实参都设置位置参数!
def test(x, y, *args):
print('x is %d, y is %d, z is %s' % (x, y, args))
test(1, 2, 3, 4, 5, 6) 结果如下: x is 1, y is 2, z is (3, 4, 5, 6)
def test(x, y, *args):
print('x is %d, y is %d, z is %s' % (x, y, args))
print(type(args))
test(1, 2) # 不传入args的值
test(1, 2, (3, 4, 5)) # 传入一个元组
test(1, 2, [3, 4, 5]) # 传入一个列表
test(1, 2, {3, 4, 5}) # 传入一个集合
test(1, 2, {1: 'lucky', 2: 'jack'}) # 传入一个字典 结果如下: x is 1, y is 2, z is ()
<class 'tuple'>
x is 1, y is 2, z is ((3, 4, 5),)
<class 'tuple'>
x is 1, y is 2, z is ([3, 4, 5],)
<class 'tuple'>
x is 1, y is 2, z is ({3, 4, 5},)
<class 'tuple'>
x is 1, y is 2, z is ({1: 'lucky', 2: 'jack'},)
<class 'tuple'> 总结:由上面代码可以看出,*args会把多传入的实参变成一个元组的类型;传入其他数据类型也一样,成为元组中的一个元素;另函数中有*args与其他形参的时候,*args一定要写到其他形参的后面,否则传入的实参都会被传入到*args当中打印成元组;还有如果没有多出传入的实参即*args没有值的时候,*args为空,不会报错。 def test(x, y, **kwargs):
print('x is %d, y is %d, z is %s' % (x, y, kwargs))
print(type(kwargs))
test(1, 2) # 不传入kwargs的值
test(1, 2, 3, 4, 5) 结果如下: Traceback (most recent call last):
x is 1, y is 2, z is {}
File '/Users/crh/PycharmProjects/app/test.py', line 11, in <module>
<class 'dict'>
test(1, 2, 3, 4, 5)
TypeError: test() takes 2 positional arguments but 5 were given def test(x, y, **kwargs):
print('x is %d, y is %d, z is %s' % (x, y, kwargs))
print(type(kwargs))
test(1, 2, name='lucky', age=18, job='IT') 结果如下: x is 1, y is 2, z is {'job': 'IT', 'name': 'lucky', 'age': 18}
<class 'dict'> **kwargs会把多出的a=b这种类型的实参打印成字典的类型(要区分开与关键参数的区别,关键参数的实参有对应的形参) test_list = [8, 9, 10, 11]
test_dict = {'name': 'lucky', 'age': '18', 'job': 'it'}
def test(x, y, *args, **kwargs):
print('x is %d, y is %d, args is %s, kwargs is %s' % (x, y, args, kwargs))
test(1, 2, test_list, test_dict) 结果如下: x is 1, y is 2, args is ([8, 9, 10, 11], {'job': 'it', 'name': 'lucky', 'age': '18'}), kwargs is {} 如上所示为什么把把字典传入函数后,打印的**kwargs为空值呢?! 是这样的,传入的字典会被当成一个元素传入函数,所有被当成多余的实参传入到了*args里面,所以**kwargs的值才为空;那么有什么办法可以把字典传入到**kwargs呢? test_list = [8, 9, 10, 11]
test_dict = {'name': 'lucky', 'age': '18', 'job': 'it'}
def test(x, y, *args, **kwargs):
print('x is %d, y is %d, args is %s, kwargs is %s' % (x, y, args, kwargs))
test(1, 2, *test_list, **test_dict) 结果如下: x is 1, y is 2, args is (8, 9, 10, 11), kwargs is {'name': 'lucky', 'job': 'it', 'age': '18'} 这下结果就是我想要的了,所以如果要把列表或者字典放到函数中,指定关键符号就好。 def change_name(name):
print('before change:', name)
name = '采菊篱下'
print('after change', name)
change_name(name)
print('在外面看看name改了么?', name) 结果如下: before change: Lucky chen
after change 采菊篱下
在外面看看name改了么? Lucky chen 全局与局部变量:
def test(x, y, z, name):
calc_age = x * y * z
print(name)
return calc_age, name
age = test(3, 2, 3, 'lucky')
print(age, type(age)) 结果如下: lucky
(18, 'lucky') <class 'tuple'> 总结:
def calc(n):
print(n)
if int(n/2) == 0:
return n
return calc(int(n/2))
calc(10)
Result:
10
5
2
1 下面我们再来看一个斐波那契数列的例子: def func(count, n1, n2): # 获取斐波那契数列第200个数字并返回给调用者
if count == 200:
return n1
n3 = n1 n2
r = func(count 1, n2, n3)
return r
ret = func(1, 0, 1)
print(ret)
Result:
173402521172797813159685037284371942044301
name2 = 'chenronghua'
def say():
name = 'lucky'
print(name)
print(name2)
say() 结果为: lucky
chenronghua 总结: 函数的作用域就是在函数里定义的变量不能被外面使用!但是外部全局定义的全局变量在函数内是可以使用的。
举个例子来说:你在房子里可以看到屋内的东西和房子外的东西,但是你在房子外面就只能看到房子外的东西不能看到房子内的东西!
原因防止在函数调用的时候防止变量冲突!
name2 = 'chenronghua'
def say():
name = 'lucky'
name2 = 'crh'
print(name)
print('function inside name2 value %s' % name2)
say()
print('function outside name value %s' % name2) 结果如下: lucky
function inside name2 value crh
function outside name value chenronghua 从上面的例子可以看出函数里面把name2的值改了,但是在外部打印还是没有发生改变,这就是函数作用域的诠释。 name2 = 'chenronghua'
def say():
global name2
name = 'lucky'
name2 = 'crh'
print(name)
print('function inside name2 value %s' % name2)
say()
print('function outside name value %s' % name2) 结果如下: lucky
function inside name2 value crh
function outside name value crh 可以看出,是可以做到的,你需要在函数体内利用内置函数global来声明你想作为全局变量的变量。 郭德纲 坚持分享的人最可爱,转起! 我为开源技术社区「带盐」,每天收获一小点,快乐生活一整天!
|
|