• 9月2号作业


    1.定义函数的方式:

    #空函数
    def func_one():
        pass
    #无参函数
    def func_two():
        print('t')
    #有参函数
    def func_three(x):
        print(x)
     
    

    2.函数的返回值:

    -1.如果函数没有返回值,则默认 返回None

    -2.函数可以通过return返回结果

    -3.return也可以终止函数的执行

    -4.return可以返回多个值(返回 类型为列表)

    3.函数的参数:

    1.形参:具有描述意义,毫无作用 (接收实参)-- (变量名)

    2.实参:具有实际的意义,具体的 一个值(传给形参)--(变量值)

    3.位置参数:

    1.位置形参: 从左到右依次写过去,就叫做位 置形参

    2.位置实参:从左到右依次写过,就叫做位置 实参,(有多少个位置形参,就必须有多少个位 置实参,从左到右依次传值)

    4.关键字参数:

    ---(位置实参加上默认值,然后按照位 置形参名传值)

    注意事项:

    1.关键字实参也必须在位置参数后面

    2.默认参数必须得放在最后面(位置参数 后面)

    默认参数:

    1.默认(默认值)形参:给位置形参一个默 认值,让他成为默认形参,以后调用 不需要为他船只,但是你为他传值的 话,他也会接收

    5.编写注册函数:

     # 1. 将用户信息保存到文件内,用户信息可保存为`nick:123|sean:456|tank:789`
    
    def register(name, pwd):
        with open('user_info.txt', 'a', encoding = 'utf-8')as f:
            f.write(f'|{name}:{pwd}')
            f.flush()
            return '注册成功!'
    name = input("请输入您的用户名: ").strip()
    pwd = input("请输入您的密码: ").strip()
            
    

    6.编写登录函数:

    #从文件内读取用户信息进行身份识别
    def login(name,password):
        with open('user_info.txt','a',encoding='utf-8') as fr:
            x_list=f.read()
            x_list=x_list.split('|')
            
            for i in x_list:
            	i =i.split(':')
                if name ==i[0] and password==i[1]:
                    return '登陆成功!'
                else:
                    return '用户名或密码错误!'
                   
    

    7.编写购物车系统:

    import os
    
    product_list = [
        ['Iphone7', 5800],
        ['Coffee', 30],
        ['疙瘩汤', 10],
        ['Python Book', 99],
        ['Bike', 199],
        ['ViVo X9', 2499],
    ]
    
    shopping_cart = {}
    current_userinfo = []
    
    db_file = r'db.txt'
    
    while True:
        print('''
    登陆
    注册
    购物
        ''')
    
        choice = input('>>: ').strip()
    
        if choice == '1':
            #1、登陆
            tag = True
            count = 0
            while tag:
                if count == 3:
                    print('尝试次数过多,退出。。。')
                    break
                uname = input('用户名:').strip()
                pwd = input('密码:').strip()
    
                with open(db_file, 'r', encoding='utf-8') as f:
                    for line in f:
                        line = line.strip('
    ')
                        user_info = line.split(',')
    
                        uname_of_db = user_info[0]
                        pwd_of_db = user_info[1]
                        balance_of_db = int(user_info[2])
    
                        if uname == uname_of_db and pwd == pwd_of_db:
                            print('登陆成功')
    
                            # 登陆成功则将用户名和余额添加到列表
                            current_userinfo = [uname_of_db, balance_of_db]
                            print('用户信息为:', current_userinfo)
                            tag = False
                            break
                    else:
                        print('用户名或密码错误')
                        count += 1
    
        elif choice == '2':
            uname = input('请输入用户名:').strip()
            while True:
                pwd1 = input('请输入密码:').strip()
                pwd2 = input('再次确认密码:').strip()
                if pwd2 == pwd1:
                    break
                else:
                    print('两次输入密码不一致,请重新输入!!!')
    
            balance = input('请输入充值金额:').strip()
    
            with open(db_file, 'a', encoding='utf-8') as f:
                f.write('%s,%s,%s
    ' % (uname, pwd1, balance))
    
        elif choice == '3':
            if len(current_userinfo) == 0:
                print('请先登陆...')
            else:
                #登陆成功后,开始购物
                uname_of_db = current_userinfo[0]
                balance_of_db = current_userinfo[1]
    
                print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' % (uname_of_db, balance_of_db))
    
                tag = True
                while tag:
                    for index, product in enumerate(product_list):
                        print(index, product)
                    choice = input('输入商品编号购物,输入q退出>>: ').strip()
                    if choice.isdigit():
                        choice = int(choice)
                        if choice < 0 or choice >= len(product_list): continue
    
                        pname = product_list[choice][0]
                        pprice = product_list[choice][1]
                        if balance_of_db > pprice:
                            if pname in shopping_cart:  # 原来已经购买过
                                shopping_cart[pname]['count'] += 1
                            else:
                                shopping_cart[pname] = {
                                    'pprice': pprice,
                                    'count': 1
                                }
    
                            balance_of_db -= pprice  # 扣钱
                            current_userinfo[1] = balance_of_db  # 更新用户余额
                            print(
                                "Added product " + pname +
                                " into shopping cart,[42;1myour current balance "
                                + str(balance_of_db))
    
                        else:
                            print("买不起,穷逼! 产品价格是{price},你还差{lack_price}".format(
                                price=pprice, lack_price=(pprice - balance_of_db)))
                        print(shopping_cart)
                    elif choice == 'q':
                        print("""
                        ---------------------------------已购买商品列表---------------------------------
                        id          商品                   数量             单价               总价
                        """)
    
                        total_cost = 0
                        for i, key in enumerate(shopping_cart):
                            print('%22s%18s%18s%18s%18s' %
                                  (i, key, shopping_cart[key]['count'],
                                   shopping_cart[key]['pprice'],
                                   shopping_cart[key]['pprice'] *
                                   shopping_cart[key]['count']))
                            total_cost += shopping_cart[key][
                                'pprice'] * shopping_cart[key]['count']
    
                        print("""
                        您的总花费为: %s
                        您的余额为: %s
                        ---------------------------------end---------------------------------
                        """ % (total_cost, balance_of_db))
    
                        while tag:
                            inp = input('确认购买(yes/no?)>>: ').strip()
                            if inp not in ['Y', 'N', 'y', 'n', 'yes', 'no']:
                                continue
                            if inp in ['Y', 'y', 'yes']:
                                # 将余额写入文件
    
                                src_file = db_file
                                dst_file = r'%s.swap' % db_file
                                with open(src_file,'r',encoding='utf-8') as read_f,
                                    open(dst_file,'w',encoding='utf-8') as write_f:
                                    for line in read_f:
                                        if line.startswith(uname_of_db):
                                            l = line.strip('
    ').split(',')
                                            l[-1] = str(balance_of_db)
                                            line = ','.join(l) + '
    '
    
                                        write_f.write(line)
                                os.remove(src_file)
                                os.rename(dst_file, src_file)
    
                                print('购买成功,请耐心等待发货')
    
                            shopping_cart = {}
                            current_userinfo = []
                            tag = False
    
                    else:
                        print('输入非法')
        elif choice == 'q':
            break
    
        else:
            print('非法操作')
    
  • 相关阅读:
    Hive安装
    hbase安装
    Spring boot 出现的时间
    RESTful Web API 实践
    Java的进阶之道
    Spring boot 注解简单备忘
    使用 xshell 登录 Windows 的 linux 子系统
    Nginx 实用配置
    跟着大彬读源码
    跟着大彬读源码
  • 原文地址:https://www.cnblogs.com/shaozheng/p/11448304.html
Copyright © 2020-2023  润新知