python之旅--函数

函数与函数式编程

1 面向对象   类-->class  

2 面向过程   过程-->def

3 函数式编程    函数-->def

数学中函数的定义:

一般的,在一个变化过程中,假设有两个变量x、y,如果对于任意一个x都有唯一确定的一个y和它对应,那么就称x是自变量,y是x的函数。x的取值范围叫做这个函数的定义域,相应y的取值范围叫做函数的值域

编程语言中函数的定义:

函数是逻辑机构化和过程化的一种编程方法。

#python中函数定义方法
def func_test():
    "the function definitions"
    x+=1
    return x

def :定义函数的关键字
func_test:函数体
(): 里面可以定义形参
"" :文档描述
x+=1:代码块或程序处理逻辑
return :定义返回值 

 函数与过程

#定义一个函数
def func_test01():
    "testing"
    print("In the func_test01")
    return 0

#定义一个过程
def func_test02():
    "Testing"
    print("In the func_test02")

#调用 函数名+括号
func_test01()
func_test02()

#过程是没有返回值的函数
#赋值变量
x = func_test01() #有返回值
y = func_test02()
print("In the func_test01 %s" %x) #In the func_test01 0
print("In then func_test02 %s" %y) #In then func_test02 None

 使用函数的好处
1.代码的重复利用
2.可扩展性,保持一致性

#模拟日志添加功能
def logger():
    with open('log.txt','a+') as f:
        f.write('end action\n')

def test1():
    print("In the test1")
    logger()

def test2():
    print("In the test2")
    logger()

def test3():
    print("In the test3")
    logger()

#调用
test1()
test2()
test3()

#优化添加功能 加上时间的功能 改变一处其它地方进行调用 
import time
def logger():
    time_format = '%Y-%m-%d %X' #时分秒
    time_current = time.strftime(time_format)
    with open('log.txt','a+') as f:
        f.write('%s end action\n' %time_current)

def test1():
    print("In the test1")
    logger()

def test2():
    print("In the test2")
    logger()

def test3():
    print("In the test3")
    logger()

#调用
test1()
test2()
test3()

 函数的返回值

返回值是为了要知道函数的执行结果,后面的程序可以根据返回值进行不同的逻辑操作。

#return和接受返回值 
def test1():
    print("In the test1")
    return 0 #碰到return会终止函数,下面的代码不会执行
    print("test end") #上面有return语句这个不会执行

test1()
#接受函数的返回值 直接赋值给变量
x = test1()
print(x) # 返回值为0

#return返回值
def test1():
    print("In the test1")

def test2():
    print("In the test2")
    return 0

def test3():
    print("In the test3")
    return 1,'A',['A','B'],{'A':'python'}

x = test1()
y = test2()
z = test3()
print(x) #None 没有定义返回值返回None 
print(y) #0
print(z) #(1, 'A', ['A', 'B'], {'A': 'python'}) 返回一个元组tuple

有参数的函数

#有参数的函数
#x y叫形参
def test(x,y):
    print(x)
    print(y)
#1,2叫实参 实际占用空间,真实存在内存中的变量
#位置参数调用 形参和实参是一一对应的关系
test(1,2)
#关键字参数调用 关键字参数可以无序
test(y=2,x=1)
#组合参数调用 位置参数要在关键字参数前面 
test(1,y=2)
test(x=1,2) #这个执行报错 位置参数在关键字参数后面

#默认参数
def test(x,y=2):
    print(x)
    print(y)

test(1) #默认参数可以不传递参数
test(1,y=3)

#参数组 实参个数不固定,定义形参
def test(*args):
    print(args)

test(1,2,3,4,5) #(1, 2, 3, 4, 5)   放到一个元组里面
test(*[1,2,3,4,5]) #(1, 2, 3, 4, 5)

#默认参数
#1.调用函数的时候,默认参数可以不传递。
#2.应用场景:如安装软件时默认安装;

def test(x,y=2):
    print(x)
    print(y)
test(1) #默认参数可以不传递参数
test(1,y=3)

#*args 参数组 实参个数不固定,定义形参
# 接受N个位置参数,转换为元组
def test(*args):
    print(args)
test(1,2,3,4,5) #(1, 2, 3, 4, 5)   放到一个元组里面
test(*[1,2,3,4,5]) #(1, 2, 3, 4, 5)
#与位置参数结合使用
def test(x,*args):
    print(x)
    print(args)
test(1,2,3,4,5,)  #1    (2, 3, 4, 5)

#**kwargs 接受字典的方式 关键字转换为字典的方式
#接受关键字参数,转换为字典
def test(**kwargs):
    print(kwargs)
    print(kwargs['name'])
test(name="A",age=22) #{'name': 'A', 'age': 22}
test(**{'name':'A','age':22}) #{'age': 22, 'name': 'A'}
#组合应用 参数组必须放在其它参数的后面
def test(name,age=18,**kwargs):
    print(name)
    print(age)
    print(kwargs)
test("test") #不指定会接受一个空字典  test {}
test("test",age=22,sex='M') #test 22 {'sex': 'M'}
test("test",sex='M',age=22) #效果同上

#综合应用
def test(name,age=18,*args,**kwargs):
    print(name)
    print(age)
    print(args)
    print(kwargs)
test('test',age=22,sex='M',job='IT')
test('test',22,'cat',sex='M',job='IT')

#前向引用
#函数action嵌套某一函数logger,该logger必须早于action函数的调用,否则报错
def action():
    print("In the action")
    logger()
action() #这个会报错

def logger():
    print("In the logger")
def action():
    print("In the action")
    logger()
action()

全局与局部变量

在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量。
全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序。
当全局变量与局部变量同名时:
在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。
#局部变量 只在函数里生效 子程序中定义的变量
def change_name(name):
    print("before change",name) #before change python
    name = "java"
    print("after change",name) #after change java
name = "python"
change_name(name)
print(name) #python

#全局变量 在一开始定义的变量为全局变量
course = 'python'
def change_name(name):
    global course #在函数里面改全局变量 禁用 
    course = 'php'
    print("before change",name,course)
    name = "java"
    print("after change",name)
name = "sql"
change_name(name)
print(name)
print(course) #php

#在子程序中定义全局变量
def change_name():
    global name #禁用
    name = "python"
change_name()
print(name) #python

#局部改全局 字符串和数字不能改
names = ["A","B","C"]
def change_name():
    names[0] = "python"
    print(names)
change_name()
print(names) #['python', 'B', 'C']

 递归

一个函数在内部调用自身,这个函数就是递归函数

递归特性:

1.必须有一个明确的结束条件。

2.每次进入更深一层递归时,问题规模相比上次递归都应有所减少

3.递归效率不高,递归层次过多会导致栈溢出。

#递归函数
def cacl(n):
    print(n)
    if int(n/2) > 0: #int可以把小数变为整数
        return cacl(n/2)
cacl(10)

高阶函数

一个函数可以接受另一个函数作为参数,这种函数称为高阶函数。

#高阶函数
def add(x,y,f):
    return f(x)+f(y)
res = add(3,-3,abs) #把abs绝对值函数当作一个参数传给函数add作为参数
print(res) #6

 匿名函数

匿名函数就是不需要显式的指定函数

#函数
def call(n):
    return n*n
print(call(10)) # 100
#转换成匿名函数
call = lambda n:n*n
print(call(10)) #100

#匿名函数主要是和其它函数搭配使用
result = map(lambda x:x**2,[1,3,5,7])
for i in result:
    print(i) #1 9 25 49

猜你喜欢

转载自www.cnblogs.com/wangzihong/p/9093092.html