代码改变世界

python基础(第二周)

2017-03-27 18:16  cnuser007  阅读(186)  评论(0)    收藏  举报

购物车小程序

一.作业需求:

1、启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表

2、允许用户根据商品编号购买商品

3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒

4、可随时退出,退出时,打印已购买商品和余额

二、代码

# -*- coding:utf-8 -*-
shopping_car =[]#定义一个购物车
product_list_tatol = "product list"
welcome = "welcome to shopping market"
product_list = [
    ('iphone',5888),
    ('lenovo',2998),
    ('cup',12),
    ('thinkpad',4500),
    ('notebook',6)
]
#商品清单
print ( welcome.center(80,"*") )
salary = input("input your salary:>>>") #输入工资
if salary.isdigit():
    salary = int(salary)#转换为整数
while True:
    print (product_list_tatol.center(80,"*"))#打印商品清单
    for item in product_list:#遍历商品清单
        print (product_list.index(item)+1,item)#打印商品清单
    choice = input("choice you want to buy,0 to exit:>>> ")#输入要购买的商口
    if choice.isdigit():
        choice = int(choice)
    if choice > 5 or choice < 0:#商品选项为0至5之间的整数
        print  ("您选的商品不存在,请重新选择")
        continue
    elif choice <=5 and choice >=1:
        if salary < product_list[choice-1][1]:#比较工资和商品价格
            print ("账户余额不足,请购买其他商品或者退出")
            continue
        else:
            pass
        item_choice = product_list[choice-1]#选择商品
        shopping_car.append(item_choice)#将商品添加到购物车
        print ("you buy goods is", shopping_car)
        salary = salary - product_list[choice-1][1]#计算余额
        print ("your balance is %d"%(salary))#打印余额

    elif choice == 0 :#退出购物,打印所购商品和余额
        print  ("you buy goods is",shopping_car,)
        print ( "your balance is %d"%(salary))
        exit()