Python学习之列表--自动超市购物车

效果图:

Python学习之列表--自动超市购物车_第1张图片

实现代码:

menu = [0,5000,500,9000,3000,30,50,7000,70,40]
name = [0,"iphone","bicycle","Mac book","Meizu S16","coffee","backpack","computer","table","chair"]
msg = """
Welcome to Mr.Zhu's shop
1.iphone 5000
2.bicycle 500
3.Mac book 9000
4.Meizu S16 3000
5.coffee 30
6.backpack 50
7.computer 7000
8.table 70
9.chair 40
0.exit
"""
money = int(input("Your Salary:"))
gets = 1
shop_list = []
spend = 0
print(msg)
while(gets):
gets = int(input("Please input the number of goods:"))
if(gets != 0):

spend = menu[gets]
if(money > spend):
shop_list.append(name[gets])
money -= spend
print("Successfully put the good in shop list,and you have remain",money)
else:
print("You not have enough money!")
else:
gets = 0
print("Welcome to come Mr.Zhu's shop again\nYou have bought :",shop_list,"\nYour remain money is:",money)

解析:
输入你的薪水,然后选择想要购买的物品,购物车自动帮告诉你账户余额并告诉你是否足够购买该商品。
很简单的两个列表,一个存价格,一个用于返回购物清单的名字,其中最开始的打印菜单可以通过循环等将两个列表结合起来打印,也可以以例子中固定模板的形式打印,循环打印代码为:
msg = 0
for i in range(0,9):
msg = i + 1
if(i == 0):
print("Welcome to Mr.Zhu's shop")
print(i+1,".",name[msg]," \t",menu[msg])
if(i == 8):
print("0 . exit")
有一点,用打印输出容易对不齐价格,因为商品名称可能有些长有些短,如果想避免这个问题:1.更改商品名称,争取几个名字字符相差不超过4个字符(\t的大小)2.增加一个判断最长名称长度的if,然后通过给短的多加\t来实现等长。

你可能感兴趣的:(Python学习之列表--自动超市购物车)