#!/usr/bin/env python # -*- coding:utf-8 -*- # products = {"iPhone X":8999,"小米笔记本":5599,"小米智能家庭套装":299,"阿迪达斯运动鞋":566} # 用字典做最外层不行,字典是无序的 # products = [{"iPhone X":8999},{"小米笔记本":5599},{"小米智能家庭套装":299},{"阿迪达斯运动鞋":566}] # 用字典做最内层也不行,循环时不容易获取键和值 products = [["iPhone X",8999],["小米笔记本",5599],["小米智能家庭套装",299],["阿迪达斯运动鞋",566]] # 内外都用列表,用索引方便取值 shopping_carts = [] #初始购物车为空 money = 0 # 初始工资为空 money += int(input("请输入您的工资:")) exit_flag = False while not exit_flag: print("\n------------商品列表-----------\n") # 商品列表 for index, product in enumerate(products): print("%s.%s %d" % (index, product[0], product[1])) print("\n-------------------------------\n") product_id = input("请输入您要购买的商品编号(输入q可退出):") if product_id.isdigit(): product_id = int(product_id) if product_id >= 0 and product_id < len(products): if money >= products[product_id][1]: money -= products[product_id][1] shopping_carts.append(products[product_id][0]) else: print("\n您的工资余额为%s元,而该商品价值%s元,不能购买!\n" % (money,products[product_id][1])) # exit_flag =True else: print("商品标号有误,请重新输入") elif product_id == "q": if len(shopping_carts) > 0: print("\n您添加到购物车的商品如下:\n") for index, product_carts in enumerate(shopping_carts): print("%s. %s" % (index, product_carts)) else: print("\n您的购物车为空!") print("\n您的工资余额为%s元!\n" % (money)) exit_flag = True
#!/usr/bin/env python # -*- coding:utf-8 -*- China = { ‘河南省‘: { ‘焦作市‘: [‘武陟‘, ‘温县‘, ‘博爱‘], ‘郑州市‘: [‘新郑‘, ‘荥阳‘, ‘中牟‘], ‘开封市‘: [‘兰考‘, ‘尉氏‘, ‘杞县‘], }, ‘广东省‘: { ‘广州市‘: [‘越秀‘, ‘荔湾‘, ‘番禺‘], ‘深圳市‘: [‘福田‘, ‘罗湖‘, ‘龙岗‘], ‘东莞市‘: [‘莞城‘, ‘南城‘, ‘东城‘], }, } exit_flag = False while not exit_flag: # 第1层循环 print("---------------------------------") print(" 欢迎您来到中国 ") print("---------------------------------") for Province in China: print(Province) print() choice_province = input("1.请输入您要前往的 省份 (输入q退出,输入b返回上级):") print() if choice_province == "q": exit_flag = True elif choice_province == "b": continue # 跳出第1层循环的剩下语句,继续进行下一次循环(选择省份) elif choice_province in China: while not exit_flag: # 第2层循环 for City in China[choice_province]: print(City) print() choice_city = input("2.请输入您要前往的 市区 (输入q退出,输入b返回上级):") print() if choice_city == "q": exit_flag = True elif choice_city == "b": break # 跳出整个第2层循环,重新进行第1层循环(选择省份) elif choice_city in China[choice_province]: while not exit_flag: # 第3层循环 for County in China[choice_province][choice_city]: print(County) print() choice_county = input("3.请输入您要前往的 县 (输入q退出,输入b返回上级):") print() if choice_county == "q": exit_flag = True elif choice_county == "b": break # 跳出整个第3层循环,重新进行第2层循环(选择市区) elif choice_county in China[choice_province][choice_city]: print("---------------------------------") print("您现在的位置是:", choice_province, choice_city, choice_county) print("---------------------------------") exit_flag = True else: print("您输入的县不存在") print() continue else: print("您输入的市区不存在") print() continue else: print("您输入的省份不存在") print() continue