• Python基础-小程序练习(跳出多层循环,购物车,多级菜单,用户登录)


    一、 从第3层循环直接跳出所有循环

    break_flag = False
    count = 0
    while break_flag == False:
        print("-第一层")
        while break_flag == False:
            print("第二层")
            while break_flag == False:
                count += 1
                if count > 10:
                    break_flag = True
                print("第三层")
    print("keep going...")
    with break_flag

    # break_flag = False
    count = 0
    while count < 3:
        print("-第一层")
        while count < 3:
            print("第二层")
            while count <= 10:
                count += 1
                # if count > 10:
                #     break_flag = True
                print("第三层")
    print("keep going...")
    without break_flag

    二、 购物车程序

    goods_list = [['Iphone7',5800],['Coffee',30],['Book',99],['Bike',199],['Vivi X9',2499]]     #商品列表
    shopping_cart = []      #用户购物车列表
    salary = int(input('input your salary:'))       #用户薪水
    m = salary
    k = 0
    
    while True:
        index = 0
        for goods in goods_list:        #打印商品列表
            print(index,goods)
            index += 1
        choice = input('>>>:').strip()
        if choice.isdigit():
            choice = int(choice)
            if choice >= 0 and choice < len(goods_list):
                goods = goods_list[choice]
                if goods[1] <= salary:      #判断用户是否带了足够的钱来支付所选商品
                    shopping_cart.append(goods)
                    salary -= goods[1]
                    print('Add goods '+str(goods[0])+' into shopping cart! Your current balance:'+str(salary))
                else:
                    print('No enough money!The price is:'+str(goods[1])+'! Need more:'+str(goods[1]-salary))
            else:
                print('Have no this goods!')
        elif choice == 'q':
            print('----------Your shopping cart----------')
            print('ID   goods   quantity    price   total')
            for i in range(len(goods_list)):
                j = shopping_cart.count(goods_list[i])
                if j > 0 :
                    k += 1
                    print(k,'	',goods_list[i][0],'	',j,'		',goods_list[i][1],'	',j * goods_list[i][1])
    
            print('Total price is:',m - salary)
            break
        else:
            print('Have no this goods')
    购物车程序

    goods_list = [['Iphone7',5800],['Coffee',30],['Book',99],['Bike',199],['Vivi X9',2499]]  # 商品列表
    shopping_cart = {}  # 用户购物车列表从列表变为字典
    salary = int(input('input your salary:'))  # 用户薪水
    # m = salary #不需要此项
    # k = 0 #用户购物车商品打印ID,移动位置至打印循环外
    
    while True:
        index = 0
        for goods in goods_list:  # 打印商品列表
            print(index, goods)
            index += 1
        choice = input('>>>:').strip()
        if choice.isdigit():  # 判断是否为数字
            choice = int(choice)
            if choice >= 0 and choice < len(goods_list):  # 商品存在
                goods = goods_list[choice]
                if goods[1] <= salary:  # 判断用户是否带了足够的钱来支付所选商品
                    if goods[0] in shopping_cart:  # 之前买过
                        shopping_cart[goods[0]][1] += 1  # 购物数量加1
                    else:
                        shopping_cart[goods[0]] = [goods[1], 1]  # 创建一条新增商品的购买记录
                    salary -= goods[1]  # 扣钱
                    print('Add goods ' + str(goods[0]) + ' into shopping cart! Your current balance:' + str(salary))
                else:
                    print('No enough money!The price is:' + str(goods[1]) + '! Need more:' + str(goods[1] - salary))
            else:
                print('Have no this goods!')
        elif choice == 'q':
            id_counter = 1  # 初始化商品ID
            total_cost = 0  # 初始化商品总花费
            print('----------Your shopping cart----------')
            print('ID   goods     quantity    price     total')
            for i in shopping_cart:
                print("%-5s%-10s%-12s%-10s%-s"
                      % (
                          id_counter, i, shopping_cart[i][1], shopping_cart[i][0],
                          shopping_cart[i][0] * shopping_cart[i][1]))
                id_counter += 1  # 商品ID自加1
                total_cost += shopping_cart[i][0] * shopping_cart[i][1]  # 用户已购商品总花费
            print('Total price is:', total_cost)
            break
        else:
            print('Have no this goods')
    购物车程序优化,使用字典

    三、多级菜单

    要求: 

    1. 打印省、市、县三级菜单
    2. 可返回上一级(b,返回)
    3. 可随时退出程序(q,退出)
    menu = {
        '北京':{
            '海淀':{
                '五道口':{
                    'soho':{},
                    '网易':{},
                    'google':{}
                },
                '中关村':{
                    '爱奇艺':{},
                    '汽车之家':{},
                    'youku':{},
                },
                '上地':{
                    '百度':{},
                },
            },
            '昌平':{
                '沙河':{
                    '老男孩':{},
                    '北航':{},
                },
                '天通苑':{},
                '回龙观':{},
            },
            '朝阳':{},
            '东城':{},
        },
        '上海':{
            '闵行':{
                "人民广场":{
                    '炸鸡店':{}
                }
            },
            '闸北':{
                '火车战':{
                    '携程':{}
                }
            },
            '浦东':{},
        },
        '山东':{},
    }
    
    
    exit_flag = False
    current_layer = menu
    
    layers = [menu]
    
    while not exit_flag:
        for k in current_layer:
            print(k)
        choice = input(">>:").strip()
        if choice == "b":
            current_layer = layers[-1]
            #print("change to laster", current_layer)
            layers.pop()
        elif choice == 'q':
            break
        elif choice not in current_layer:
            continue
        else:
            layers.append(current_layer)
            current_layer = current_layer[choice]
    View Code

    四、用户登陆程序

    需求:

    1. 最多允许用户尝试登陆3次
    2. 当同一用户名3次密码均不正确时,锁定该用户
     1 with open('account',encoding='utf8') as f_account, open('lockedlist', 'a+') as f_locked:
     2     l = []                  #定义用户名验证列表,存放黑名单数据
     3     f_locked.seek(0)        #"a+"模式打开后,文件位置位于末尾,要遍历文件内容,需要将指针移至文件起始位置
     4     for locked_info in f_locked.readlines():    #遍历黑名单
     5         l.append(locked_info.strip())                   #将黑名单数据添加进列表,注意:需要将文件中的换行符脱掉
     6 
     7     c = []                  #定义用户登录名列表,存储用户尝试的登录名
     8     count = 1               #登陆次数计数器
     9     flag = True             #登陆循环控制开关
    10     while flag and count < 4:
    11         user = input('Please input username:')      #输入用户名
    12         pwd = input('Please input password:')       #输入用户密码
    13         if user in l:                 #用户名在黑名单中
    14             print("This user is in blacklist,can't log in!")    #打印提示信息
    15             continue
    16         c.append(user)
    17         for info in f_account:                  #用户名不在黑名单中,遍历用户登陆文件
    18             user_name, user_pwd = info.strip().split(',')       #将文件中的用户名和登陆密码赋值给判定变量
    19             if user == user_name:               #用户名符合
    20                 if pwd == user_pwd:             #对应密码符合
    21                     print('Welcome %s' % user)  #打印登陆成功信息
    22                     flag = False               #登陆成功,跳出登陆程序
    23                     break
    24                 count += 1                      #对应密码不符合,while循环计数器加1
    25                 break
    26             count += 1                          #用户名不符合,while循环计数器加1
    27             break
    28     if count == 4:                              #如果不同用户名密码输错3次,关闭程序
    29         print('More than 3 times wrong!')       #打印提示信息
    30     if len(c) == 3 and c[0] == c[1] == c[2]:    #如果相同用户名密码输错3次,将该用户名加入黑名单,限制登陆
    31         print('This user has been locked!')
    32         f_locked.write(user+'
    ')               #将错误3次的用户名写入黑名单,注意,加换行符
    用户登陆程序

  • 相关阅读:
    JS的type类型为 text/template
    Vue之x-template(2)
    Vue之x-template(1)
    vue之$mount
    console.log()与console.dir()
    Less用法注意事项
    一次 Linux 系统被攻击的分析过程
    WebAR 如何改变增强现实的未来
    开发中的测试名词解释
    Flutter 同步系统的 HTTP 代理设置
  • 原文地址:https://www.cnblogs.com/OldJack/p/6642196.html
Copyright © 2020-2023  润新知