大鹏

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

作业1:多级菜单

    三级菜单
    可依次选择进入各子菜单
    所需新知识点:列表、字典

打印省、市、县三级菜单
可返回上一级
可随时退出程序
menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}



tag=True
while tag:
    menu1=menu
    for key in menu1: # 打印第一层
        print(key)

    choice1=input('第一层>>: ').strip() # 选择第一层

    if choice1 == 'b': # 输入b,则返回上一级
        break
    if choice1 == 'q': # 输入q,则退出整体
        tag=False
        continue
    if choice1 not in menu1: # 输入内容不在menu1内,则继续输入
        continue

    while tag:
        menu_2=menu1[choice1] # 拿到choice1对应的一层字典
        for key in menu_2:
            print(key)

        choice2 = input('第二层>>: ').strip()

        if choice2 == 'b':
            break
        if choice2 == 'q':
            tag = False
            continue
        if choice2 not in menu_2:
            continue

        while tag:
            menu_3=menu_2[choice2]
            for key in menu_3:
                print(key)

            choice3 = input('第三层>>: ').strip()
            if choice3 == 'b':
                break
            if choice3 == 'q':
                tag = False
                continue
            if choice3 not in menu_3:
                continue

            while tag:
                menu_4=menu_3[choice3]
                for key in menu_4:
                    print(key)

                choice4 = input('第四层>>: ').strip()
                if choice4 == 'b':
                    break
                if choice4 == 'q':
                    tag = False
                    continue
                if choice4 not in menu_4:
                    continue

                # 第四层内没数据了,无需进入下一层
三级菜单面条版
menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}



#part1(初步实现):能够一层一层进入
layers = [menu, ]

while True:
    current_layer = layers[-1]
    for key in current_layer:
        print(key)

    choice = input('>>: ').strip()

    if choice not in current_layer: continue

    layers.append(current_layer[choice])



#part2(改进):加上退出机制
layers=[menu,]

while True:
    if len(layers) == 0: break
    current_layer=layers[-1]
    for key in current_layer:
        print(key)

    choice=input('>>: ').strip()

    if choice == 'b':
        layers.pop(-1)
        continue
    if choice == 'q':break

    if choice not in current_layer:continue

    layers.append(current_layer[choice])
三级菜单文艺青年版

ccroz版本

参考 wanghui1991 :https://www.cnblogs.com/wanghui1991/p/5724278.html

 

主干代码:

##三级菜单字典定义
zone = {
    "甘肃省": {
        "张掖市": ["甘州区", "民乐县", "山丹县"],
        "武威市": ["凉州区", "古浪县", "民勤县"],
    },
    "山东省": {
        "济南市":["历下区","长清区","禹城市"],
        "潍坊市":["昌乐县","潍城区","寒亭区"]
    },
    "陕西省": {
        "西安市":["雁塔区","新城区","未央区"],
        "咸阳市":["礼泉县","秦都区","渭城区"]
    }
}

for key1  in zone:
    print(key1)
choice1  = input('>>:')
if choice1 == 'q':
    print('退出')
if choice1 in zone:
    for key2 in zone[choice1]:
        print(key2)

choice2 = input('>>:')
if choice2 =='q':
    print('退出')
if choice2 =='b':
    print('返回上层目录')
if choice2 in zone[choice1]:
    for key3 in zone[choice1][choice2]:
        print(key3)

 

之后再加上标志位 和while循环,就差不多了

##三级菜单字典定义
zone = {
    "甘肃省": {
        "张掖市": ["甘州区", "民乐县", "山丹县"],
        "武威市": ["凉州区", "古浪县", "民勤县"],
    },
    "山东省": {
        "济南市":["历下区","长清区","禹城市"],
        "潍坊市":["昌乐县","潍城区","寒亭区"]
    },
    "陕西省": {
        "西安市":["雁塔区","新城区","未央区"],
        "咸阳市":["礼泉县","秦都区","渭城区"]
    }
}
##退出循环标志位定义
exit_flag = True
while exit_flag:
    for i in zone:   #读取第一级菜单
        print(i)
    choice = input("first,press q to exit:")  #第一级菜单输入
    if choice == "q":
        exit_flag =False
    if choice in zone:
        while exit_flag:
            for i2 in zone[choice]:     #第二级菜单读取
                print("\t\t",i2)
            choice2 = input("second,press b return back and q to quit!!!:") #第二级菜单输入
            if choice2 == 'b':
                break
            elif choice2 == 'q':
                exit_flag = False

            if choice2 in zone[choice]:
                while exit_flag:
                    for i3 in zone[choice][choice2]:
                        print("\t\t\t\t",i3)
                    choice3 = input("last one,press b return back and q to quit!!!")  #第三级菜单输入
                    if choice3 == 'b':
                        break
                    elif choice3 == "q":
                        exit_flag=False

 

 

 Alex课堂演示:

zone = {
    "甘肃省": {
        "张掖市": {"甘州区": "民乐县"},
        "武威市": ["凉州区", "古浪县", "民勤县"],
    },
    "山东省": {
        "济南市":["历下区","长清区","禹城市"],
        "潍坊市":["昌乐县","潍城区","寒亭区"]
    },
    "陕西省": {
        "西安市":["雁塔区","新城区","未央区"],
        "咸阳市":["礼泉县","秦都区","渭城区"]
    }
}

current_layer = zone  #实现动态循环
parent_layers = []  #保存所有的父级,最后一个元素永远都是父级

while True:
    for key in current_layer:
        print(key)
    choice = input(">>:").strip()
    if len(choice)==0:continue
    if choice in current_layer:
        parent_layers.append(current_layer) #在进入下一层之前,把当前层(也就是下一层父级)追加到列表中,
        # 下次loop,当用户选择b的选择,就可以直接取列表的最后一个值出来就OK了
        current_layer = current_layer[choice] #改成了子层
    elif choice =='b':
        if parent_layers:
            current_layer=parent_layers.pop() #取出列表的最后一个值,因为它就是当前层的父级
    else:
        print('无此项')

 

 

 

 

 

 

 

#作业二:请闭眼写出购物车程序
#需求:
用户名和密码存放于文件中,格式为:egon|egon123
启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额

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('\033[45m尝试次数过多,退出。。。\033[0m')
                break
            uname = input('用户名:').strip()
            pwd = input('密码:').strip()

            with open(db_file,'r',encoding='utf-8') as f:
                for line in f:
                    line=line.strip('\n')
                    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('\033[48m登陆成功\033[0m')

                        # 登陆成功则将用户名和余额添加到列表
                        current_userinfo=[uname_of_db,balance_of_db]
                        print('用户信息为:',current_userinfo)
                        tag=False
                        break
                else:
                    print('\033[47m用户名或密码错误\033[0m')
                    count+=1

    elif choice == '2':
        uname=input('请输入用户名:').strip()
        while True:
            pwd1=input('请输入密码:').strip()
            pwd2=input('再次确认密码:').strip()
            if pwd2 == pwd1:
                break
            else:
                print('\033[39m两次输入密码不一致,请重新输入!!!\033[0m')

        balance=input('请输入充值金额:').strip()

        with open(db_file,'a',encoding='utf-8') as f:
            f.write('%s,%s,%s\n' %(uname,pwd1,balance))

    elif choice == '3':
        if len(current_userinfo) == 0:
            print('\033[49m请先登陆...\033[0m')
        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,\033[42;1myour current\033[0m 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('\n').split(',')
                                        l[-1]=str(balance_of_db)
                                        line=','.join(l)+'\n'

                                    write_f.write(line)
                            os.remove(src_file)
                            os.rename(dst_file,src_file)

                            print('购买成功,请耐心等待发货')

                        shopping_cart={}
                        current_userinfo=[]
                        tag=False


                else:
                    print('输入非法')


    else:
        print('\033[33m非法操作\033[0m')
购物车程序面条版

 













posted on 2018-11-23 23:38  pf42280  阅读(183)  评论(0)    收藏  举报