需求:
• 啓動程序後讓用戶輸入工資,然後打印商品列表
• 允許用戶根據商品編號購買商品
• 用戶選擇商品後,檢測餘額是否足夠,夠就直接扣款,不夠就提醒 • 用戶可一直購買商品,也可以隨時退出,退出時,打印已經購買的商品和餘額
class Shopping(object):
def __init__(self, salary):
#工資金額
self.salary = salary
#商品列表
self.commodity_list = {"C001":"book","C002":"phone","C003":"milk"}
#商品價格字典
self.price_dict = {"C001":4,"C002":100,"C003":8}
#購物車列表
self.so_list = []
#打印商品及價格
def print_commodity_price(self):
for c in self.commodity_list:
print('商品:{},價格:{}'.format(c,self.price_dict[c]))
#購買商品
def shopping_commodity(self):
while salary>0:
sp = input('根據商品編號購買商品')
print(type(self.price_dict[sp]),sp)
if sp=='q':
break
if self.price_dict[sp] > self.salary:
print('根據商品編號購買商品,工資不夠了')
break
else:
self.so_list.append(sp)
self.salary -= self.price_dict[sp]
print('剩餘金額:',self.salary)
if self.salary ==0:
break
#打開購物車列表
def shopping_list(self):
print('購買到的商品:',self.so_list)
print('剩餘金額:',self.salary)
if __name__ == '__main__':
while True:
try:
salary = int(input('用戶輸入工資:'))
break
except:
continue
s = Shopping(salary)
s.print_commodity_price()
s.shopping_commodity()
s.shopping_list()