python第五篇——函数和函数式编程

 一、函数的定义和调用

# 1,定义格式:

# def 函数名([形参列表]):

#     '''注释'''

#     函数体

# return  结果

#

# 2,注意事项

# (1)函数的定义位置必须位于调用函数的全局之前;

# (2)实参列表必须与函数定义的形参列表一一对应。

 

二、函数的参数类型与传递

#注意:默认参数:默认值参数必须出现在函数参数列表的最右端,且任何一个默认值参数右边不能有非默认值参数。

#调用带有默认值参数的函数时,可以不对默认值参数进行赋值,也可以赋值,具有较大的灵活性

def say( message, times =1 ):

    print(message * times)

say('hello')

##hello

say('hello',3)

##hellohellohello



def demo(newitem,old_list=[]):

    old_list.append(newitem)

    return old_list

print(demo('a'))

##['a']

print(demo('b'))

##['a', 'b']

#默认参数old_list的取值发生变化old_list=[‘a’],因old_list是可变对象仍然指向[‘a’],第二次不解释old_list,继续重复使用上一次的默认参数值



#解决方案:

def demo(newitem,old_list=None):

    if old_list is None:

        old_list=[]

    old_list.append(newitem)

    return old_list

print(demo('a'))

##['a']

print(demo('b'))

##['b']

 

###问题:写一个函返回所有数(个数不确定)的和???

<二>、动态参数

1,位置动态参数

#        *形参

# 将函数接收到的多余位置参数当做一个元组给形参。

def my_fun1(x,*arg):

    print(arg)

my_fun1(1,2,3,4)

##(2, 3, 4)

 

2,关键字动态参数

# **形参

# 将函数接收到的多余关键字参数当做一个字典给形参。

def my_fun2(x,**arg):

    print(arg)

my_fun2(x=1,y=2,z=3)

##{'y': 2, 'z': 3}

 

<三>、参数传递的序列解包

#序列:字符串,列表,元组,字节流。

def demo(a, b, c):

    print(a+b+c)

lis=[1,2,3] #列表

demo(*lis)

##6

 

#参数序列的解包顺序1,序列解包相当于位置参数,需要优先处理,

#demo(a=1,*(2,3))

# Traceback (most recent call last):

#   File "C:/Users/86130/Desktop/PYCHARM/随意.py", line 727, in <module>

#     demo(a=1,*(2,3))

# TypeError: demo() got multiple values for argument 'a'

demo(c=1,*(2,3))

##6

#参数序列的解包顺序2,序列解包在关键参数解包之前

def demo(a, b, c):

    print(a,b,c)

#demo(**{'a':1, 'b':2}, *(3,)) ##error

demo(*(3,), **{'c': 1, 'b': 2})

##3 2 1

 

<四>、return语句

# 如果函数没有return语句,或者有return语句但是没有执行到,或者只有return而没有返回值,Python将认为该函数以return None结束。

# 若有多个返回值,多个返回值以逗号相隔。

 

三、变量的作用域

# global与nonlocal关键字

# 在函数体中引用全局变量时,若该变量名是在函数体中第一次出现且在赋值语句之前,则解释为局部变量,除非使用global进行了声明。

m=100

n=200

def f():

    print(m+5)

    n=n+5  ##error,local variable 'n' referenced before assignment

f()

#105

 

1,global 将局部变量转变为全局变量。

def demo():

global x

x = 3

y =4

print(x,y)

x=5

demo()

## 3 4

print(x)

##3

print(y) #error

 2,nonlocal关键字.在嵌套函数中若为定义在上一级函数体中的局部变量赋值,使用nolocal表明该变量不是所在块的局部变量而是上级函数体重定义的全局变量。

count = 1

def fun_in():

    count = 12

fun_in()

print(count)

#1

def func():

    count = 1

    def fun_in():

        nonlocal count

        count = 12

    fun_in()

    print(count)

func()

#12

#关键字nonlocal声明的变量会引用距离最近的非全局作用域的变量,要求声明的变量已经存在,关键字nonlocal不会创建新变量。

四、递归函数和匿名函数

1.递归函数

#例 非整数的阶乘定义为:n!=n×(n-1) ×(n-2) ×…×2×1

def factorial(n):

    if n == 1:

        return 1

    return n * factorial(n - 1)

for i in range(1,10): #输出1~9的阶乘

    print(i,'! =', factorial(i))

 

2,匿名函数

#匿名函数是没有名称的函数,即不使用过def语句定义的函数,而使用lamda关键字。

sum = lambda arg1, arg2: arg1 + arg2;

 # 调用sum函数

print ("相加后的值为 : ", sum( 10, 20 )) # 相加后的值为 :  30

print ("相加后的值为 : ", sum( 20, 20 )) # 相加后的值为 :  40

五、常用内置函数

<一>,随机函数

#??

<二>,map()函数

#map函数的作用是以参数序列中的每个元素分别调用function函数,把每次调用后返回的结果保存为对象。

def func (x):

    x=x+2

    return x

result = map(func, [1,2,3,4,5])

print(list(result))

#[3, 4, 5, 6, 7]

result= map(lambda x,y:x+y,[1,2,3],[4,5,6])

print(list(result))

##[5, 7, 9]

<三>,filter()函数

#filter函数会对指定序列执行过滤操作

def func (x):

    x=x%2

    return x

result = filter(func, [1,2,3,4,5])

print(list(result))

##[1, 3, 5]

 

<四>,reduce()函数

# reduce函数会对参数序列中的元素进行累积。

# reduce函数的定义如下:from functools import reduce

# reduce(function, iterable[, initializer])

# function是一个带有两个参数的函数;

# iterable是一个可迭代对象;

# initializer表示固定的初始值。

from functools import reduce

func = lambda x,y:x+y

result = reduce(func, [1, 2, 3, 4, 5])

print(result) ##15

 

<五>,内置排序函数soted()

#sorted() 函数对所有可迭代的对象(字符串、列表、元组、字典集合等)进行排序操作。

#在默认情况下sorted函数接收的参数是元组时,它将会先按元组的第一个元素进行排序再按第二个元素进行排序,再按第三个、第四个…依次排序。

a=[5,4,3,1,1]

b=['f','b','g','d','c']

list(zip(a,b))

c = sorted(zip(a, b))

print(c)

##[(1, 'c'), (1, 'd'), (3, 'g'), (4, 'b'), (5, 'f')]

 

<六>,range()函数

#range() 函数可创建一个整数列表,一般用在 for 循环中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

季沐晴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值