本文共 2610 字,大约阅读时间需要 8 分钟。
需求 要求用户输入总资产,例如:2000 显示商品列表,让用户根据序号选择商品,加入购物车 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。 附加:可充值、某商品移除购物车
测试信息goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998},]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | goods = [ { "name" : "电脑" , "price" : 1999 }, { "name" : "鼠标" , "price" : 10 }, { "name" : "游艇" , "price" : 20 }, { "name" : "美女" , "price" : 998 }, ] # 定义函数,格式化菜单输出 def menu(): count = 0 for i in goods: print ( '【{0}】 {1} {2}' . format (count,i[ 'name' ],i[ 'price' ])) count + = 1 # 定义购物车空列表 goods_list = [] tag = True while tag: money = input ( 'How much are you ?' ).strip() # 判断输入的数据类型 if money.isdigit() and len (money) ! = 0 : money = int (money) while tag: menu() choice = input ( '请输入你要购买的商品序号:' ).strip() if choice.isdigit() and len (choice) ! = 0 : choice = int (choice) if choice > = 0 and choice < = 3 : # 取出所买商品的信息 g_l = [] for i in goods: g_l.append({i[ 'name' ]: i[ 'price' ]}) info = g_l[choice] price_list = list (info.values()) price = int (price_list[ 0 ]) name_list = list (info.keys()) # 使用a的值来控制下面两层while循环 a = 1 while a = = 1 : if money > = price: money = money - price print ( '商品已加入购物车,当前余额为{}' . format (money)) goods_list.append(name_list[ 0 ]) while a = = 1 : print ( '当前购物车里商品:' ,goods_list) choices = input ( ''' 【E】 结账 【D】 删除商品 【S】 继续购买 请选择:''' ).strip().lower() if choices ! = 'e' and choices ! = 'd' and choices ! = 's' : print ( '选择错误,请重新输入:' ) continue if choices = = 's' : a = 0 break if choices = = 'e' : print ( '已结账,当前余额为{}' . format (money)) a = 0 tag = False if choices = = 'd' : print (goods_list) delet = input ( '请输入你想删除的商品:' ).strip() if delet in goods_list: goods_list.remove(delet) print ( '%s 删除成功!' % delet) continue else : print ( '此商品不在购物车' ) continue else : print ( '你买不起这个,请选择:' ) choicess = input ( ''' 【A】 重新选择商品 【B】 充值 【C】 退出 请选择:''' ).strip().lower() if choicess = = 'a' : a = 0 if choicess = = 'c' : exit() while a = = 1 : if choicess = = 'b' : recharge = input ( '请输入充值金额:' ).strip() if recharge.isdigit() and len (recharge) ! = 0 : recharge = int (recharge) money = money + recharge print ( '充值成功,当前金额为:' ,money) break else : print ( '充值金额有误' ) continue else : print ( '没有此商品,请重新选择' ) continue else : print ( '你的输入有误,请输入数字:' ) continue 本文转自lyndon博客51CTO博客,原文链接http://blog.51cto.com/lyndon/1947432如需转载请自行联系原作者 迟到的栋子 |