一、匿名函数

没有函数名的函数

lambda x,y(参数):x+y(逻辑代码#返回值)

print((lambda x, y: x** y)(2, 4))
16

通常与max()、sorted()、filter()、sorted()方法联用。

max(可迭代对象,key=func)

max(iterable, *[, default=obj, key=func]) -> value max(arg1, arg2, *args, *[, key=func]) -> value

salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}
def func(res):
    return salary_dict[res]
max_salary = max(salary_dict, key=func)  # 根据函数的返回值比较
print(max_salary)
jason
salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}
max_salary = max(salary_dict, key=lambda key : salary_dict[key])  # 根据函数的返回值比较
print(max_salary)
jason

排序sorted(可迭代对象)

sorted(iterable: Iterable[SupportsLessThanT], /, *, key: None=..., reverse: bool=...) -> List[SupportsLessThanT]

lis = [1, 5, 6, 3, 99, 3955, 55, 3, 4, 7, 661]
print(sorted(lis))
[1, 3, 3, 4, 5, 6, 7, 55, 99, 661, 3955]
salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}

# 根据函数的返回值排序
sorted_salary = sorted(salary_dict, key=lambda key: salary_dict[key])
print(sorted_salary)
['sean', 'nick', 'tank', 'jason']

映射 map() #返回的是一个迭代器

map(func, *iterables) --> map object

salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}

print(list(map(lambda x: f'{x}dsb', salary_dict)))  # list()将迭代器转化为列表
['nickdsb', 'jasondsb', 'tankdsb', 'seandsb']

过滤filter() #返回的是一个迭代器

filter(function or None, iterable) --> filter object

lis = ['jdaod','ndao','nafonp','jonjod','qccxi','njefo']
print(list(filter(lambda x: x.endswith('od'),lis)))
['jdaod', 'jonjod']

二、内置函数

解码字符bytes()

bytes(iterable_of_ints) -> bytes bytes(string, encoding[, errors]) -> bytes bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer bytes(int) -> bytes object of size given by the parameter initialized with null bytes bytes() -> empty bytes object

print('你好啊'.encode('utf-8'))
res = bytes('你好啊', 'utf-8')
print(res)
b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x95\x8a'
b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x95\x8a'

ASCII码转化chr()&ord()

print(ord('a'))
print(ord('A'))
print(chr(97))
print(chr(65))
97
65
a
A

分栏divmod(x,y)>>>>>(x\ \y,x%y)

divmod(x: _N2, y: _N2, /) -> Tuple[_N2, _N2]

print(divmod(10,3))
print(divmod(9,4))
(3, 1)
(2, 1)

带有索引的迭代enumerate()

lis = ['q', 'w', 'e']
for i in enumerate(lis):
    print(i)
(0, 'q')
(1, 'w')
(2, 'e')

把字符串翻译成数据类型eval()

eval(source: Union[str, bytes, CodeType], globals: Optional[Dict[str, Any]]=..., locals: Optional[Mapping[str, Any]]=..., /) -> Any

lis = '["你好",1,2,"再见"]'
lis_eval = eval(lis)
print(lis_eval)
print(type(eval('16468')))
['你好', 1, 2, '再见']
<class 'int'>

哈希hash() # 可变不可哈希,不可变可哈希

hash(obj: object, /) -> int

#返回给定对象的哈希值。两个比较相等的对象必须具有相同的哈希值,但反过来则不一定成立。

print(hash(1))
print(hash('611'))
1
-4211130100363174742

全真则真all()

print(all([1, 2, 3, 0]))
print(all([]))
False
True

一真则真any()

print(any([1, 2, 3, 0]))
print(any([]))
True
False

二进制、八进制、十六进制bin()&oct()&hex()

print(bin(17))
print(oct(17))
print(hex(17))
0b10001
0o21
0x11

列举出所有功能dir()

import math

print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'sumprod', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

三、面向过程编程

按照一定的顺序,顺序的每一步都可以看成函数,顺序中的每一步都可以看作一个函数这个函数的输入是上个函数的输出

优点:复杂的问题流程化,进而简单化。

缺点:扩展性差。

def input_username_pwd():
    username = input('请输入账号:')
    psd = input('请输入你的密码:')

    return username, psd
def save_file_a(f,content):
    with open(f,'a',encoding='utf-8') as fa:
        fa.write(content)
    return True

def save_file_w(f,content):
    with open(f,'w',encoding='utf-8') as fw:
        fw.write(content)
    return True

def read_file(f):
    with open(f,'r',encoding='utf-8') as fr:
        data = fr.read().split('\n')
    return data

def move(): # 修改购物车
    mo = input(r'修改购物车(r)\清空购物车(c)\退出(q):')
    if mo == 'c':
        global shopping_car_dict
        shopping_car_dict = {}
        print('购物车已清空')
        shopping()
    elif mo == 'r':
        while 1:
            for x,y in enumerate(shopping_car_dict):
                print(x,y)
            shopping_car_list = [y for x,y in enumerate(shopping_car_dict)]
            goods_revise = input('请选择你要修改的商品编号:(q结束修改)').strip()
            if goods_revise == 'q':
                return
            revised_goods = shopping_car_list[int(goods_revise)]
            goods_num = input('你要修改数量为:').strip()
            if goods_num == '0':
                del shopping_car_dict[revised_goods]
            else:
                shopping_car_dict[revised_goods] = int(goods_num)
    elif mo == 'q':
        return

triggle = 0 #  是否已登陆
shopping_car_dict = {} #  存储选择的的商品
loger_info = ['','']
'''..................................................................
'''

def register():
    while 1:
        username,psd = input_username_pwd()
        for i in read_file(r'D:\桌面\ATM\username_pwd.txt'):
            if username == i.split(':')[0]:
                print('账号已存在!请再次输入')
                break
        else:
            save_file_a('username_pwd.txt',f'\n{username}:{psd}:0')
            print('注册成功!!')
            return
def login():
    count = 0
    while count < 3:
        username,psd = input_username_pwd()
        for i in read_file(r'D:\桌面\ATM\username_pwd.txt'):
            if username == i.split(':')[0] and psd == i.split(':')[1]:
                if int(i.split(':')[3]) == 1:
                    print('账号已锁定,无法登录!')
                    return
                else:
                    print(f'欢迎!{username}')
                    loger_info[0] = i.split(':')[0]
                    loger_info[1] = int(i.split(':')[2])
                    print(f'您的余额为:{loger_info[1]}')
                break
        else:
            print('账号或密码错误,请重试')
            count += 1
            choice = input(r'是否注册?Y\N>>>>')
            if choice == 'Y':
                register()
                return
            elif choice == 'N':
                continue
            else:
                print('非法输入!')
                continue
        global triggle
        triggle = 1
        return
    else:
        print('密码错误超三次,账号已锁定!')
def shopping():
    global triggle
    if triggle == 0:
        print('您还未登录,不能购物!')
        return
    goods_dict ={
       '0':('炸土豆',3),
       '1':('奶茶',15),
       '2':('冰激淋',7),
       '3':('甜甜圈',20),
       '4':('焦糖布丁',13),
       '5':('超大份炸鸡',50),
       'q':'退出'
    }
    while 1 :
        for x,y in goods_dict.items():
            print(x,y)
        shopping_choice = input('请输入你想购买的商品:(q# 退出)').strip()
        if shopping_choice == 'q':
            return
        elif shopping_choice not in goods_dict:
            print('非法输入!')
            continue
        else:
            num = input('请输入你要购买的商品数量:(q# 退出)').strip()
            if num == 'q':
                break
            elif not num.isdigit():
                print('非法输入!')
                continue
            else:
                if goods_dict[shopping_choice][0] not in shopping_car_dict:
                    shopping_car_dict[goods_dict[shopping_choice][0]] = [goods_dict[shopping_choice][1],int(num)]
                else:
                    shopping_car_dict[goods_dict[shopping_choice][0]][1] += int(num)
                print(f'你选择的{num}份{goods_dict[shopping_choice][0]}已加入购物车')
                continue
def shopping_car():
    global triggle
    if triggle == 0:
        print('您还未登录,不能购物!')
        return
    tatal = 0
    if shopping_car_dict == {}:
        print('购物车是空的,快去逛逛吧!')
        return
    print('你的购物车有以下商品')
    for i,j in shopping_car_dict.items():
        print(i,j)
        tatal += j[0]*j[1]
    print(f'总计价格为{tatal}')
    move()
    choice = input('是否结账?(Y/N)')
    if choice == 'Y':
        check()
    elif choice == 'N':
        return
def check():
    global triggle
    if triggle == 0:
        print('您还未登录,不能购物!')
        return
    tatal = 0
    print(f'您的购物清单:')
    for i,j in shopping_car_dict.items():
        print(i,j)
        tatal += j[0]*j[1]
    if loger_info[1] < tatal:
        print('余额不足,请整理购物车')
        shopping_car()
    else:
        choice = input(r'是否现在结算?(Y\N)')
        if choice == 'Y':
            global yu
            yu = loger_info[1] - tatal
            print(f'结算完成,您的余额剩余{yu}')
        elif choice == 'N':
            shopping()
            return
    print(f'总计价格为{tatal}')
    print(f'您的余额为{yu}')
def lottery():
    pass
def goods_back():
    pass
def coupon(): # 优惠券
    pass  
def shopping_history():
    pass


# 功能选择

func_dict= {
    0: register,
    1: login,
    2: shopping,
    3: shopping_car,
    4: check,
    5: lottery,
    6: goods_back,
    7: coupon,  # 优惠券
    8: shopping_history
}

func_ts= '''
    0: 注册,
    1: 登录,
    2: 购物,
    3: 购物车,
    4: 结账,
    5: 抽奖,
    6: 退货,
    7: 优惠券,
    8: 消费记录
    q: 退出
'''
while 1:
    print(func_ts)
    print('*'*50)
    func_choice = input('请输入你想要使用的功能:').strip()
    if func_choice == 'q':  # 退出
        break
    if not func_choice.isdigit():
        print('非法输入')
        continue
    int_func_choice = int(func_choice)
    if int_func_choice not in func_dict:
        print('非法输入')
        continue
    func_dict[int_func_choice]()  # 正常选择功能

    
    

posted on 2025-08-04 14:13  新月绘影  阅读(15)  评论(0)    收藏  举报