Python使用列表进行简单的购买系统

Python使用列表进行简单的购买系统

用python初学的列表等概念,可以做最基本的购物系统(单纯流程控制):

1.启动程序让用户输入工资,之后打印商品列表;
2.商品使用编号进行购买;
3.购买商品时进行余额检测,够直接扣款,不够则提醒;
4.可随时退出,退出时打印商品;
  1. 自己写的:
salary=int(input("Please input your salary:"))
list=[(1,"notebook",5),(2,"laptop",5000),(3,"cup",10),(4,"iphone",8399)]
list2=[]
count=0
while count<1:
    for item in list:
        print(item)
    no=int(input("Which good do you want to buy ? "))
    if no==list[no-1][0]:
        if salary >=list[no-1][2]:
            salary=salary-list[no-1][2]
            list2.append(list[no-1][1])
        else:
            print("You salary is not enough !")
    else:
        print("Don't have the good")
    count=count+1
    choose=input("Do you want to continue to buy ? Y or N")
    if choose == "Y" or choose=="y":
        count=0
    else:
        break
print("Your shopping list :",list2,"Your salary :",salary)
'''
  1. 老师写的:

    product_list = [
       ('Iphone',5800),
       ('Mac Pro',9800),
       ('Bike',800),
       ('Watch',10600),
       ('Coffee',31),
       ('Alex Python',120),
    ]
    shopping_list = []
    salary = input("Input your salary:")
    if salary.isdigit():
       salary = int(salary)
       while True:
           for index,item in enumerate(product_list):
               #print(product_list.index(item),item)
               print(index,item)
           user_choice = input("选择要买嘛?>>>:")
           if user_choice.isdigit():
               user_choice = int(user_choice)
               if user_choice < len(product_list) and user_choice >=0:
                   p_item = product_list[user_choice]
                   if p_item[1] <= salary: #买的起
                       shopping_list.append(p_item)
                       salary -= p_item[1]
                       print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m" %(p_item,salary) )
                   else:
                       print("\033[41;1m你的余额只剩[%s]啦,还买个毛线\033[0m" % salary)
               else:
                   print("product code [%s] is not exist!"% user_choice)
           elif user_choice == 'q':
               print("--------shopping list------")
               for p in shopping_list:
                   print(p)
               print("Your current balance:",salary)
               exit()
           else:
               print("invalid option")

相比之下:

  • 在流程控制中,只进行了简单的控制。没有做到随时退出,在一些if-else的语句中,缺乏else,一旦与if语句条件冲突会直接退出程序或者报错。
  • 我使用的商品编号是在列表中列表中嵌套列表,嵌套列表中有编号,我觉得这个比下面所使用的index和enumerate相比,显得low了很多,但是利于理解。毕竟初学者写的代码也就利于理解。
  • 下面的代码中,在余额检测不足中,在print语句里加了红底,这个,很秀。
  • 在最后打印已购清单中,本来我就应该使用类似与下面的格式,打印出的已购清单才显得清晰,虽然目的一样,但是对于一个程序来说,结果有时候比过程重要,美观占很大地位。
  • 我觉得下面代码中index应该+1,才不会造成有代码编号是0的情况。

猜你喜欢

转载自blog.csdn.net/THTBOOM/article/details/79619404