python购物车程序的简单程序优化版

# Author:barry allen
# -*- coding:utf-8 -*-
shop_list=[("IPHONE",8000),("MI",5000),("NOKIA",1200),("HUAWEI",2400),("CHINA",4100)]
salary=input("请输入您的存款:")
if salary.isdigit():
    salary=int(salary)
bought_list=[]    #已购买手机的清单
while True:
    for index,data in enumerate(shop_list):
        print(index,data)
    user_choice=input("请输入您需要购买的手机编号,若您不想购买,请输入q退出系统!")
    if user_choice.isdigit():
            user_choice=int(user_choice)
            if user_choice>=0 and user_choice<len(shop_list):
               tem=shop_list[user_choice]                   #tem为临时变量,用于比较是否能继续购买
               if tem[1]<=salary:
                salary-=tem[1]
                bought_list.append(tem)                     #调用列表函数.append(),此时传进去的元素是一个整体,作为新列表的子列表
                print("已完成购买,您当前的余额为\033[41;1m%s\033[0m" % (salary))
               else:
                     print("余额不足,请重新选择!")
            else:
                print("没有该手机编号,请重新选择!")
    elif user_choice=='q':
            print("--------已购买的手机清单---------")
            for data in bought_list:
                print(data)
            print("您的余额为\033[31;1m%s\033[0m" % (salary))
            print("谢谢购买,欢迎下次光临!")
            exit()
    else:
            print("输入错误的信息,请重新选择")

 小结:

1.输出列表带编号(下标)的方法:

for index,data in enumerate(shop_list)

    print(index,data) 

其中,index,data分别为编号(下标)和元素,相比于之前的购物车小程序,省去了在列表中标出各个手机产品的编号]

2.高亮表示法的标准格式以及参数;

#高亮:
标准格式为 '\033[?;?;?m%s\033[0m' % (xxx)
其中,问号为以下三种格式中分别任选一种
特殊显示方式 :0(默认值)、1(高亮)、22(非粗体)、4(下划线)、24(非下划线)、 5(闪烁)、25(非闪烁)、7(反显)、27(非反显)
字体颜色:30(黑色)、31(红色)、32(绿色)、 33(黄色)、34(蓝色)、35(洋 红)、36(青色)、37(白色)
背景色:40(黑色)、41(红色)、42(绿色)、 43(黄色)、44(蓝色)、45(洋 红)、46(青色)、47(白色)
如以下程序
test="this is a test"
print('\033[31;1;42m%s\033[0m' %(test))   #其中,三种参数的顺利并无作要求
print('\033[34;1;42m你好\033[0m')         #也可以写中文,不需要引用字符串变量

3.判断是否为数字的函数,并将其转换为整数型

#判断是否为数字,*.isdigit()
salary=input(salary)
if salary.isdigit():
   salary=int(salary)          #如果为数字,则转换为整数类型;

猜你喜欢

转载自www.cnblogs.com/god-for-speed/p/10858668.html