Python基础9(笔记)——函数

1.定义方法

def 函数名(参数)

2.调用方法

函数名('参数')

3.函数的返回值

return

当Python达到函数的尾部时仍然没有遇到return语句,就会自动返回None。

4.函数的参数

1)形参和实参

2)函数文档

例子如下:

可以设置默认值(参数)

3)位置参数和关键字参数

关键字参数常用于指定默认值或可选参数。

5.函数与过程

过程无返回值,函数有返回值

Python只有函数,没有过程。

Python是动态地确定类型,C等变成语言定义时:function(int a),Python不需要。

6.局部变量&全局变量

def discounts(price,rate):
    final_price = price * rate
    return final_price
old_price = float(input("请输入原价:"))
rate = float(input("请输入折扣率:"))
new_price = discounts(old_price,rate)
print("打折后的价格是:",new_price)

def discounts(price,rate):
    final_price = price * rate
    return final_price
old_price = float(input("请输入原价:"))
rate = float(input("请输入折扣率:"))
new_price = discounts(old_price,rate)
print("打折后的价格是:",new_price)
print("这里试图打印局部变量final_price的量:", final_price)

 final_price是局部变量!

def discounts(price,rate):
    final_price = price * rate
    old_price = 50
    print("修改后的old_price的值是1:",old_price)
    # python重新创建一个局部变量,与全局变量的old_price不同,虽然名字相同,但是互不影响
    return final_price
old_price = float(input("请输入原价:"))
rate = float(input("请输入折扣率:"))
new_price = discounts(old_price,rate)
print("修改后的old_price的值是2:", old_price)
print("打折后的价格是:",new_price)

 7.内嵌函数和闭包

1)global关键字

count = 5
def Myfunction():
    count = 10
    print(10)
Myfunction()
# 输出为10
print(count)
#输出仍为5
count = 5
def Myfunction():
    global count
    # 将函数中的count改为全局变量
    count = 10
    print(10)
Myfunction()
# 输出为10
print(count)
#输出为10

2)内嵌(内部)函数

def fun1():
    print("fun1()正在被调用...")
    def fun2():
        print("fun2()正在被调用...")
    fun2()
fun1()

 3)闭包:从形式上定义为:如果在一个内部函数里,对外部作用域(但不是在全局作用域进行引用)那内部函数就被认为是闭包。

def FunX(x):
    def FunY(y):
        return x * y
    return FunY
# FunY是一个闭包

8.lambda表达式

1)匿名函数:用于简单脚本书写时使用;lambda不需要考虑命名问题;简化代码可读性

def ds(x):
    return 2 * x + 1
ds(5)
Out[4]: 11
lambda x : 2 * x + 1
Out[5]: <function __main__.<lambda>(x)>
g = lambda x : 2 * x + 1
g(5)
Out[7]: 11
# 该匿名函数用完之后内存垃圾清洁器会自动删除
# 不需要申请和释放资源
#两个参数
def add(x,y):
    return x+y
add(3,4)
Out[8]: 7
lambda x,y : x+y
Out[9]: <function __main__.<lambda>(x, y)>
g = lambda x,y : x+y
g(3,4)
Out[11]: 7
def fun1(some_list,f):
    return [f(x) for x in some_list]
ints = [4,0,1,5,6]
fun1(ints,lambda x : x * 2)
Out[12]: [8, 0, 2, 10, 12]

# 不使用lambda:
def fun2(some_list):
    return [x * 2 for x in some_list]
ints = [4,0,1,5,6]
fun2(ints)
Out[14]: [8, 0, 2, 10, 12]

 

2)过滤器

filter()函数:根据判断结果,自动过滤掉不符合条件的元素

 定义函数输出10以内的奇数:

def odd(x):
    return x % 2
temp = range(10)
show = filter(odd,temp)
list(show)
Out[4]: [1, 3, 5, 7, 9]

#法二
list(filter(lambda x : x % 2,range(10)))
Out[5]: [1, 3, 5, 7, 9]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值