Python-Level1-day09:变量作用域;函数参数

0 作业与复习

"""
    封装成函数
"""
​
list_commodity_infos = [
    {"cid": 1001, "name": "屠龙刀", "price": 10000},
    {"cid": 1002, "name": "倚天剑", "price": 10000},
    {"cid": 1003, "name": "金箍棒", "price": 52100},
    {"cid": 1004, "name": "口罩", "price": 20},
    {"cid": 1005, "name": "酒精", "price": 30},
]
​
list_orders = [
    {"cid": 1001, "count": 1},
    {"cid": 1002, "count": 3},
    {"cid": 1005, "count": 2},
]
​
​
# (1)定义函数,打印所有商品信息,
# 格式:商品编号xx,商品名称xx,商品单价xx.
def print_comodity(dict_commodity_info):
    for item in dict_commodity_info:
        print("商品编号 :%s 商品名称 :%s  商品单价:%s" % (
            item["cid"], item["name"], item["price"]))
​
print_comodity(list_commodity_infos)
print("1-----------------------")
​
​
# 2. 定义函数,打印所有订单中的信息,
# 格式:商品编号 xx,购买数量 xx.
def print_order(list_order):
    for item in list_order:
        print("商品编号  : %s  购买数量: %s"
              % (item["cid"], item["count"]))
​
print_order(list_orders)
print("2-----------------------")
​
​
# (3)定义函数,打印所有订单中的商品信息,
# 格式:商品名称xx,商品单价:xx,数量xx.
def print_all(dict_commodity, list_orders):
    for item in list_orders:
        for item1 in dict_commodity:
            if item["cid"] == item1["cid"]:
                print("商品名称:%s  商品单价: %s 数量%s."
                      % (item1["name"], item1["price"], item["count"]))
​
print_all(list_commodity_infos, list_orders)
print("3-----------------------")
​
# 4. 查找数量最多的订单(使用自定义算法,不使用内置函数)
max_order = list_orders[0]
for item in list_orders:
    if item["count"] > max_order["count"]:
        max_order = item
print(max_order)
print("4-----------------------")
​
# 5. 根据购买数量对订单列表降序(大->小)排列
for i in range(len(list_orders) - 1):
    for j in range(i + 1, len(list_orders)):
        if list_orders[i]["count"] < list_orders[j]["count"]:
            list_orders[i], list_orders[j] = list_orders[j], list_orders[i]
print(list_orders)
​

# 定义函数,计算社保缴纳费用.
​
def func01(salary_before_tax):
    return salary_before_tax * (0.08
           + 0.02 + 0.002 + 0.12) + 3
​
print("个人需要缴纳社保费用:" + str(func01(1000)))
​

"""
5. 定义函数,根据颜色(RGBA),打印描述信息
​
"""
​
​
def colour(key):
    colour1 = {
        "R": "红色",
        "G": "绿色",
        "B": "蓝色",
        "A": "透明度"
    }
    if key in colour1:
        return colour1[key]
    return None  # 不写默认也返回它
​
​
print(colour('R'))
​

# 6. 定义函数,在数字列表中获取最小值
def minx(list01):
    min1 = list01[0]
    for i in range(1, len(list01)):
        if min1 > list01[i]:
            min1 = list01[i]
    return min1
​
​
a = [1, 2, 4, 4, 6, 2, 0]
print(minx(a))
​
#7. 定义函数,对数字列表进行升序排列
list1 = [5, 15, 25, 35, 1, 2]
​
​
def sort_up(list01):
    for r in range(len(list01) - 1):
        for c in range(r + 1, len(list01)):
            if list01[r] > list01[c]:
                list01[r], list01[c] = list01[c], list01[r]
​
​
sort_up(list1)
print(list1)
​

"""
练习4:定义函数,将列表中大于某个值的元素设置为 None
​
"""
​
​
def set(list01):
    for i in range(len(list01)):
        if list01[i] > 10:
            list01[i] = None
​
​
list1 = [34, 545, 56, 7, 78, 8]
set(list1)
print(list1)
​
"""
   字典排序:转化成列表排序---面试考点
"""
​
list001 = {'a': 5, 'b': 15, 'c': 25,
           'd': 35, 'e': 1, 'f': 2}
print(list(list001.items()))
​
​
def sort_up(list01):
    listdata = list(list01.items())
    for r in range(len(listdata) - 1):
        for c in range(r + 1, len(listdata)):
            if listdata[r][1] > listdata[c][1]:
                listdata[r], listdata[c] = listdata[c], listdata[r]
    return dict(listdata)
​
​
print(sort_up(list001))
​

1 作用域 LEGB

  1. 作用域:变量起作用的范围。

  1. Local 局部作用域:函数内部使用。

  1. Enclosing 外部嵌套作用域 :函数嵌套。

  1. Global 全局作用域:模块(.py 文件)内部。(单个文件内部使用)

  1. Builtin 内置模块作用域:builtins.py 文件。(C代码实现的文件,里面的函数与变量在哪都能用,全领域的使用)

变量名的查找规则

  1. 由内到外:L -> E -> G -> B

  1. 在访问变量时,先查找本地变量,然后是包裹此函数外部的函数内部的变量,之后是全局变量,最后是内置变量。

    局部变量

  1. 定义在函数内部的变量(形参也是局部变量)

  1. 只能在函数内部使用

  1. 调用函数时才被创建,函数结束后自动销毁

全局变量

  1. 定义在函数外部,模块内部的变量。

  1. 在整个模块(py 文件)范围内访问(但函数内不能将其直接赋值)。

global 语句

  1. 作用:在函数内部修改全局变量。或者在函数内部定义全局变量(全局声明)。

  1. 语法:global 变量 1, 变量 2, …

  1. 说明:在函数内直接为全局变量赋值,视为创建新的局部变量。

    不能先声明局部的变量,再用 global 声明为全局变量。

nonlocal 语句

  1. 作用:在内层函数修改外层嵌套函数内的变量

  2. 语法 nonlocal 变量名 1,变量名 2, ...

  1. 说明:在被嵌套的内函数中进行使用

"""
 作用域规范
    最上面写全局变量
    然后写函数定义
    最后调用函数
​
"""
​
b = 20# 全局变量
​
​
def func01():
    a = 10  # 局部变量,在函数内部创建的变量,只能函数内部用
    print(b)  # 局部作用域可以读取全局变量,只要全局变量在这个函数调用之前
​
    # b = 200   Python认为创建一个局部变量b 而不是修改全局变量
    # global b
    # b = 2000  # 如果非要在局部作用域修改全局变量需要加globa说明
​
​
func01()
# print(a) 函数结束,栈帧消失,局部变量也随之消失
​
​
​

"""
    内存图理解作用域
"""
​
data01 = 10
​
​
def func01(p):
    global data01
    data01 += 1
    p += 1
​
​
data02 = 10
func01(data02)
func01(data02)
print(data01)  # 12
print(data02)  # 10
​
data = [10]
​
​
# 修改列表全局变量不需要global,用索引即可
def func02():
    data[0] = 100  # 读取全局变量,寻地址修改第一个元素
    # data = [20] 希望修改但修改不了,需要global声明
​
func02()
print(data)
​

​​​​​​​

 

"""
   读代码从入口代码main开始看,不是一上去就看函数与变量
"""
​
list_commodity_infos = [
    {"cid": 1001, "name": "屠龙刀", "price": 10000},
    {"cid": 1002, "name": "倚天剑", "price": 10000},
    {"cid": 1003, "name": "金箍棒", "price": 52100},
    {"cid": 1004, "name": "口罩", "price": 20},
    {"cid": 1005, "name": "酒精", "price": 30},
]
​
list_orders = [
    {"cid": 1001, "count": 1},
    {"cid": 1002, "count": 3},
    {"cid": 1005, "count": 2},
]
​
​
# (1)定义函数,打印所有商品信息,
# 格式:商品编号xx,商品名称xx,商品单价xx.
def print_comodity(dict_commodity_info):
    for item in dict_commodity_info:
        print("商品编号 :%s 商品名称 :%s  商品单价:%s" % (
            item["cid"], item["name"], item["price"]))
​
​
# 2. 打印所有订单中的信息,
# 格式:商品编号 xx,购买数量 xx.
def print_order(list_order):
    for item in list_order:
        print("商品编号  : %s  购买数量: %s"
              % (item["cid"], item["count"]))
​
​
# (3)定义函数,打印所有订单中的商品信息,
# 格式:商品名称xx,商品单价:xx,数量xx.
def print_all(dict_commodity, list_order):
    for item in list_orders:
        for item1 in list_commodity_infos:
            if item["cid"] == item1["cid"]:
                print("商品名称:%s  商品单价: %s 数量%s."
                      % (item1["name"], item1["price"], item["count"]))
​
​
# 4. 查找数量最多的订单(使用自定义算法,不使用内置函数)
max_order = list_orders[0]
for item in list_orders:
    if item["count"] > max_order["count"]:
        max_order = item
​
# 5. 根据购买数量对订单列表降序(大->小)排列
for i in range(len(list_orders) - 1):
    for j in range(i + 1, len(list_orders)):
        if list_orders[i]["count"] < list_orders[j]["count"]:
            list_orders[i], list_orders[j] = list_orders[j], list_orders[i]
​
​
def main():
    while True:
        i = input(">>")
        if i == "1":
            print_comodity(list_commodity_infos)
        elif i == "2":
            print_order(list_orders)
        elif i == "3":
            print_all(list_commodity_infos, list_orders)
​
​
# -------------------------入口代码----------------------
main()
​
# ctrl+shift + 加减  进行代码函数折叠

2 函数参数

实参传递方式 argument

位置传参定义:实参与形参的位置依次对应。

序列传参定义:实参用*将序列拆解后与形参的位置依次对应。

关键字传参定义:实参根据形参的名字进行对应。

字典关键字传参

  1. 定义:实参用**将字典拆解后与形参的名字进行对应。

  1. 作用:配合形参的缺省参数,可以使调用者随意传参。形参定义方式 parameter

缺省形参

  1. 语法:

def 函数名(形参名 1=默认实参 1, 形参名 2=默认实参 2, ...):

函数体

  1. 说明:

缺省参数必须自右至左依次存在,如果一个参数有缺省参数,则其右侧的所有

参数都必须有缺省参数。

缺省参数可以有 0 个或多个,甚至全部都有缺省参数。

"""
    函数实际参数
"""
​
def func01(p1, p2, p3):
    print(p1)
    print(p2)
    print(p3)
​
​
# 必须从右边向左依次存在
# func02(p1=0, p2, p3)直接报错
# func02(p1, p2, p3=0) 不报错
def func02(p1=1, p2=" a", p3=0.1):
    print(p1)
    print(p2)
    print(p3)
​
​
# 1 位置实参:按照顺序与形参对应,参数必填
func01(1, 2, 3)
​
# 2 关键字实参:按照名字与形参对应,不需要顺序,参数必填
func01(p1=1, p3=3, p2=2)
func01(1, p3=3, p2=2)
​
# 3 默认形参:即实参可选填
# 关键字实参的优点是可以在默认形参的情况下通过实参修改形参
func02(p2="b")
func02(2)
​

"""
练习:定义函数,根据小时、分钟、秒,计算总秒数
调用:提供小时、分钟、秒
调用:提供分钟、秒
调用:提供小时、秒
调用:提供分钟
"""
​
def fun01(hour=0, min=0, second=0):
    return hour * 3600 + min * 60 + second
​
print(fun01(1, 1, 1))
print(fun01(1,min=1, second=2))
#print(fun01(2,min=1,2))不支持这样写法
print(fun01())

"""
    函数形式参数
"""
​
# 1 *号元组形参
# 实参数量无线多传递给形参  并且只支持位置实参,不支持关键字实参
def func01(*p1):
    print(p1)
​
​
# 2 **号字典形参
# 实参数量无线多传递给形参  并且只支持关键字实参,只支持关键字实参
def func02(**p1):
    print(p1)
​
​
# 3 万能参数
def fun03(*args, **kwargs):
    print(args)
    print(kwargs)
​
​
func01()  # () 打印元组
func01(1, 2, 3)  # (1, 2, 3)
# func01(p1 =1)不支持关键字实参
​
​
func02()
func02(p1=1)  # {'p1': 1} 打印字典
func02(p1=1, p2=2)  # {'p1': 1, 'p2': 2}  打印字典
​
fun03()  # () {}
fun03(1, 2, 3)  # (1, 2, 3) {}
fun03(p1=2, p2=3)  # ()  {'p1': 2, 'p2': 3}
fun03(1, 2, 3, p1=2, p2=3)  # (1, 2, 3) {'p1': 2, 'p2': 3}
# fun03(1, 2, 3, p1=2, p2=3,4,p4 =2) 先位置后键字,不能交叉传递
​

"""
练习:定义数值累乘的函数
"""
​
# 不定长参数:目的是调用者更加方便
​
def func(*p):
    res = 1
    for item in p:
        res *= item
    return res
​
​
# 有利于调用者,不用单独传入容器参数,直接传递需要操作多个数据
# 自动化合成容器
print(func(1, 2, 3, 4))
​

"""
    函数实际参数:拆
"""
​
​
def func01(p1, p2, p3):
    print(p1)
    print(p2)
    print(p3)
​
​
list01 = [1, 2, 3]
# func01(list01) 报错:另外两个参数没有传递
func01(*list01)  # 1 2 3  一个字 :拆容器的元素,传递给位置实参,因此数量要对应上
func01(*"dpq")  # d p q
​
dict01 = {'a': 1, 'b': 2, 'c': "3"}
func01(*dict01)  # 拆建 a b c
​
dict02 = {'p2': 1, 'p1': 2, 'p3': 3}  # 键与形参需要相同,不过位置可以改变
func01(**dict02)  # 2 1 3  拆值
​

"""
    函数形式参数;命名关键字形参
​
            必须写上关键字实参
"""
​
​
# p1 叫命名关键字形参,他的实参必须是关键字实参
#作用是让传递的参数更加明确
def func01(*agrs, p1):
    print(agrs)
    print(p1)
​
​
# 例如 print(*args, sep=' ', end=' ')
func01(1, 2, p1=2) #(1,2) 2
print(1, 2, 3, 4)
​

"""
函数参数
    实际参数:怎么对应问题
        位置实参:根据顺序与形参对应 func(1,2)
        关键字实参:根据名字与形参对应 func(p1 =1 ,p2 =2)
        序列实参:func(*[a,b,c]) func(*"abc") ----拆
        字典实参:func(**字典)  --拆  (关键字要与建相同)
​
    形式参数
        位置形参:def func(p1,p2) --必填
        默认形参:def func(p1 = 1,p2 = " ")
        *元组形参:def func(*agrs)  ---合
        **字典新参:def func(**kwargs) ---合
        命名关键字形参:def func(*ages,p1)   --必须是关键字实参
​
​
"""

作业

作业
1. 三合一
2. 当天练习独立完成
3. 容器综合训练
    -- 将下列代码定义为函数
    -- 在终端中根据输入的选项,调用相应功能
​
# 员工列表(员工编号 部门编号 姓名 工资)
dict_employees = {
    1001: {"did": 9002, "name": "师父", "money": 60000},
    1002: {"did": 9001, "name": "孙悟空", "money": 50000},
    1003: {"did": 9002, "name": "猪八戒", "money": 20000},
    1004: {"did": 9001, "name": "沙僧", "money": 30000},
    1005: {"did": 9001, "name": "小白龙", "money": 15000},
}
​
# 部门列表
list_departments = [
    {"did": 9001, "title": "教学部"},
    {"did": 9002, "title": "销售部"},
    {"did": 9003, "title": "品保部"},
]
​
# 打印所有员工信息,
for eid, emp in dict_employees.items():
    print(f"{emp['name']}的员工编号是{eid},部门编号是{emp['did']},月薪{emp['money']}元.")
​
# 打印所有月薪大于2w的员工信息,
for eid, emp in dict_employees.items():
    if emp['money'] > 20000:
        print(f"{emp['name']}的员工编号是{eid},部门编号是{emp['did']},月薪{emp['money']}元.")
​
# 在部门列表中查找编号最小的部门
min_value = list_departments[0]
for i in range(1, len(list_departments)):
    if min_value["did"] > list_departments[i]["did"]:
        min_value = list_departments[i]
print(min_value)
​
# 根据部门编号对部门列表降序排列
for r in range(len(list_departments) - 1):  # 0
    for c in range(r + 1, len(list_departments)):  # 1234
        if list_departments[r]["did"] < list_departments[c]["did"]:
            list_departments[r], list_departments[c] = list_departments[c], list_departments[r]
print(list_departments)
​
4.(选做)定义函数,将列表中奇数删除
    测试数据:[3,7,5,6,7,8,9,13]
    提示:在列表中删除多个元素,倒序删除
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

dpq666dpq666

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

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

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

打赏作者

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

抵扣说明:

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

余额充值