[ Python -1 ] 简易购物车程序

练习:

  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('***********************')
View Code

主要练习点:

  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('33[31;1m输入编号错误,请重新输入33[1m')
    elif int(choice) > len(goods_list) or int(choice) < 1:
        print('33[31;1m编号不在商品列表中33[1m')
    else:
        choice_buy = int(choice) -1
        if salary >= goods_list[choice_buy][1]:
            print('33[32;1m购买成功.33[1m')
            salary = salary - goods_list[choice_buy][1]
        else:
            print('33[31;1m购买失败33[1m')
            break
View Code
原文地址:https://www.cnblogs.com/hukey/p/6961826.html