练习:
1. 要求用户输入总资产,例如:2000
2. 显示商品列表,让用户根据序号选择商品,加入购物车
3. 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
goods = [{'name':'电脑', 'price':1999},{'name':'鼠标', 'price':10},{'name':'游艇', 'price':20},{'name':'玩具', 'price':998},] p1 = int(input('enter your money:')) while True: if not isinstance(p1, int): raise TypeError('bad type.') for i in goods: print(goods.index(i), i) p2 = int(input('enter your price:')) if p2 == 0: p1 = p1 - int(goods[p2]['price']) if p1 < 0: print('余额不足。') break else: print('***********************') print('当前余额:', p1) print('***********************') elif p2 == 1: p1 = p1 - int(goods[p2]['price']) # print(p3) if p1 < 0: print('余额不足。') break else: print('***********************') print('当前余额:', p1) print('***********************') elif p2 == 2: p1 = p1 - int(goods[p2]['price']) # print(p3) if p1 < 0: print('余额不足。') break else: print('***********************') print('当前余额:', p1) print('***********************') elif p2 == 3: p1= p1 - int(goods[p2]['price']) # print(p3) if p1 < 0: print('余额不足。') break else: print('***********************') print('当前余额:', p1) print('***********************') else: print('***********************') print('商品序号错误,请重新输入。') print('***********************')
主要练习点:
1. 列表(list)、字典(dist) 类型灵活运用。
2. 条件判断while 、 if ... break
修改一版:
# -*- coding: utf-8 -*- goods_list = [ ['computer', 5000], ['apple', 500], ['pen', 50], ] salary = float(input('enter your salary:')) while True: for index, item in enumerate(goods_list, 1): print(index, item) choice = input('enter your choice:') if choice == 'q': break if choice.isdigit() == False: print('