函数式编程python_python之函数式编程

函数的返回值,函数的返回值可以不返回,也可以只返回一个值。当有多个返回值的时候,可以以元组的形式返回。

def test1():

print('in the test1')

def test2():

print('in the test2')

return 0

def test3():

print('in the test3')

return 1,'hello',['alex','wupeiqi'],{'name':'alex'}

#return test2

x=test1()

y=test2()

z=test3()

print(x)

print(y)

print(z)

有参数形式的函数

def test5(x,y): #可以设置默认参数def test5(x=1,y=10):

print(x)

print(y)

test5(y = 5,x = 1) #与形参顺序无关

test5(5,1) #与形参顺序一一对应

#test5(x = 5,1) #有位置参数,又有关键字调用,则按照位置参数调用,关键字参数是不能写在位置参数前面的

test5(5,y = 1)

#默认参数特点:默认参数可有可无,默认参数非必须传递

#用途:1.默认值,此变量可以在调用函数时不传递

#上面的函数在调用时,传递实参的数量只能比形参少,不能比形参多

针对传递的实参数量不固定,可以传递参数组

def test(x,*args): #'*'表示传递的实参数量不固定

print(args)

print('the number of membe is %s'%x)

#*args接受的是位置参数,不能接受关键字参数,转换成元组的形式

#函数调用

test(4,2,3,4,5)

test(5,*[1,2,3,4,6])

#**kwargs把n个关键字参数,转换成字典的方式

def test2(**kwargs):

print(kwargs)

print(kwargs['name'])

print(kwargs['age'])

test2(name = 'shunge',age = '28')

test2(**{'name': 'shunge', 'age': '28'})

import time

def logger(source):

time_format = '%y-%m-%d,%X'

time_current = time.strftime(time_format)

print('time:%s'%time_current, 'from %s'%source)

def test3(name,age = 28,**kwargs):

print(kwargs)

print(name)

print(age)

logger('test3') #函数之间的调用

test3('shunge',sex = 5,age = '4')

#函数式编程

#*现在的函数多定义的是一段代码执行的过程

#*函数式编程:更接近于数学运算,一种抽象程度很高的编程范式,纯粹的函数式编程是没有

#*变量的,只要输入是确定的,则输出就是确定,python对函数式编程部分支持,python对

于学习函数式编程不是一个很好的选择

#****函数的局部变量与全局变量

#在子称程序中定义的变量时全局变量,在程序定义开始前的变量称为全局变量

#全局变量与局部变量同名时,存在程序内部局部变量起作用,其他地方全局变量起作用

names = ["alex","two","three"]

name_tuple =(1,2,3,4) #元组

def change_name():

names[0] = "金角大王"

print('inside func',names)

change_name()

print(names)

#****高阶函数

#变量可以指向函数,函数的参数可以接收另一个函数作为参数,这种函数称之为高阶函数

def add(x,y):

return x+y

def mul(x,y):

return x*y

def deal(x,y,f,f1):

return f(x,y)+f1(x,y)

z = deal(5,7,add,mul)

print(z)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值