python入门3——函数

1.如何定义一个函数?
def 函数名():
功能
结束!
2.如何调用一个函数?
函数名()
结束!

>>> def lili():
 print('nice!')
 >>> lili()
nice!
>>> 

3.默认返回是元组

>>> def dingjie():
 return 1,2,'jie'
 >>> dingjie()
(1, 2, 'jie')

4.函数的局部变量:

def discount(price,rate):
    final_price = price*rate
    return final_price
#其中final_price是局部变量,在外部是不可以调用的
old_price=float(input('原价'))
rate=float(input('折扣率'))
new_price=discount(old_price,rate)
print('打折后单价',new_price)

注意点:局部变量仅仅在def_return之间有作用,除此之外,是没有用的,但是你在def中间可以把局部变量输出,或者跟全局变量用同一个名字。总而言之,就是def内部可以用,外部不可以用!
5.函数中定义函数
重点:空格,除了大函数可以调用小函数之外,小函数不能外部直接调用!

def dj1():
    print('dj1()正在被调用')
    def dj2():
      print('dj2()正在被调用')#在dj1内部声明一个函数,
    dj2()#在dj1()内部调用这个函数,注意只能在这里调
  >>> dj1()
dj1()正在被调用
dj2()正在被调用

6.闭包
函数内部的调用

def fun1(x):
    def fun2(y):
        return x*y
    return fun2
    >>> i=fun1(2)
>>> type(i)
<class 'function'>#说明i是一个函数关于y
>>> i=3
>>> i=fun1(2)
>>> i(3)
6
>>> fun1(2)(3)
6
>>> 

注意:子函数是不可以对主函数中定义的变量修改的,除非你在子程序中用nonlocal声明。

def fun1():
    x=1;
    def fun2():
        nonlocal x
        x*=x
        return x
    return fun2()
>>> fun1()
1
>>>   

7.匿名函数
方式
lambda 参数:返回值

>>> lambda x:2*x+1
<function <lambda> at 0x0000020EC971C1E0>
>>> g=lambda x:2*x+1
>>> g(1)
3
#就相当于定义一个函数!

8.filter——过滤器
格式: filter(函数,原数据)

>>> def odd(x):
 return x%2
 >>> temp=range(10)
>>> show=filter(odd,temp)
>>> list(show)
[1, 3, 5, 7, 9]
其实就是
>>> list(filter(lambda x :x%2,range(10)))
[1, 3, 5, 7, 9]

9.map——映射

>>> list(map(lambda x:x+2,range(10)))
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
发布了20 篇原创文章 · 获赞 4 · 访问量 3954

猜你喜欢

转载自blog.csdn.net/weixin_43475628/article/details/101156967