三级菜单作业,优化,保存在文件; 购物车,充值,重复购买等

三级菜单作业:

1、菜单内容保存在文件 menu

  menu内容:

  {'jiangsu': {'wuxi': {'宜兴':{'官林':{}}, 'jiangying':{}, 'xishan':{}}, 'nanjing': {'qixia', 'gulou', 'changning', 'zhongshan'}},
'zhejiang': {'嘉兴': {'a2', 'a3', 'a4'},'宁波': {'a1', 'a2', 'a3'}},
'guangzhou': {1: {'a'}, 2: {'b'}, 3:{'c'}}
}  

2、用函数取menu内容,转化内容为字典格式;   函数: eval()

3、菜单优化方式做逻辑结构;

with open('menu') as poem:
    f=poem.read()
dic_city=eval(f)
# print(type(dic_city))
last_layer=[]
current_layer=dic_city
while True:
    for i in current_layer:
        print(i)
    choice = input('pls input your next_destion:').strip()
    if len(choice)==0:continue
    if choice in current_layer:
        # print(choice)
        last_layer.append(current_layer)
        current_layer = current_layer[choice]
        # print(last_layer)
        # print(current_layer)
    if choice=='b' and last_layer:
        # if last_layer:
        current_layer = last_layer[-1]
        last_layer.pop()

 
 # 商品信息- 数量、单价、名称
 #    2. 用户信息- 帐号、密码、余额
 #    3. 用户可充值
 #    4. 购物历史信息
 #    5. 允许用户多次购买,每次可购买多件
 #    6. 余额不足时进行提醒
 #    7. 用户退出时 ,输出档次购物信息

file--->products内容:

[['iphone',5000,50],['book',120,50],['bike',1500,50],['coffee',30,50],['ticket',80,50]]

f = open('products','r',encoding='utf8')
product_list = eval(f.read())

your_cart={}
temp_list=[]


salary = input('select your_salary :')
if salary.isdigit():
    salary = int(salary)
while True:
    for i in enumerate(product_list):
        print(i)
    your_choice = input('input your_choice:').strip()
    if your_choice.isdigit():
        your_choice = int(your_choice)
        if your_choice >=0 and your_choice < len(product_list):
            product = product_list[your_choice]
            if product[1] < salary:
                if product[0] in your_cart:
                    your_cart[product[0]][1] +=1
                else:
                    your_cart[product[0]] = [product[1],1]
                salary -=product[1]
                print(your_cart)
            else:
                print('Your salary is no enough,to recharge input c :')
    if your_choice == 'c':
        salary_charge = input('recharge:').strip()
        if salary_charge.isdigit():
            salary_charge=int(salary_charge)
            salary += salary_charge
    if your_choice == 'q':
        print("what are in your cart:%s"%your_cart)
        break
原文地址:https://www.cnblogs.com/santizhou/p/7418871.html