#usr/bin/env/python3
# -*- coding: utf-8 -*-
#编写购物车
class account(object):
def __init__(self):
self.cash=50000.0
self.__stocklist=[]
def get(self):
return self.cash
def add(self,value):
self.cash+=value
def minus(self,value):
self.cash-=value
def refresh_account(self):
print('***Account Information:')
print('***Your Cash:%10.2f'%self.cash)
index=0
for item in self.__stocklist:
index+=1
print('***Your Stock%d\tName:%s\tPrice:%10.2f'%(index,item[0],item[1]))
def add_stock(self,stock_name,stock_price):
self.__stocklist.append([stock_name,stock_price])
class shopping(object):
def __init__(self):
pass
self.__stock={
'Iphone7' :[2,5000],
'MacPro' :[2,15000],
'Kindle' :[5,1000],
'Bike' :[2,2000],
}
def list_items(self):
print('***Number\tItems:\tStock:\tPrice:***')
i=0
for items in list(self.__stock.items()):
print("***%d\t%s\t\t%d\t\t%10.2f"%(i,items[0],items[1][0],items[1][1]))
i+=1
def waiting(self,usr_account):
while True:
self.list_items()
usr_order=input('***Which one do you want to buy?Enter Number:')
#退出机制
if(usr_order in ['q','quit','exit']):
print('Let\'s check your account again.')
usr_account.refresh_account()
print('Thank you very much. Have a nice day. Bye.')
exit()
#输入检查
try:
OrderNum=int(usr_order)
if OrderNum>=len(self.__stock) or OrderNum<0:
print('***Input Error, your input is not in range.')
continue
except ValueError:
print('***Input Error, You can only input an integer.')
continue
#判断账户余额是否足够
cur_stock=list(self.__stock.items())[OrderNum]
if cur_stock[1][1]>usr_account.get():
print('***You don\'t have enough money.Please check your account.')
continue
else:
usr_account.minus(cur_stock[1][1])
usr_account.add_stock(cur_stock[0],cur_stock[1][1])
print('***Pay Sucess.\n***You spent %10.2f RMB to buy a %s'%(cur_stock[1][1],cur_stock[0]))
usr_account.refresh_account()
self.__stock[cur_stock[0]][0]=self.__stock[cur_stock[0]][0]-1
if self.__stock[cur_stock[0]][0]<=0:
del self.__stock[cur_stock[0]]
if(self.__stock=={}):
print('Ooooooops,you bought the shop out. Shop Closed.Bye.')
usr_account.refresh_account()
exit()
shop=shopping()
cur_usr=account()
shop.waiting(cur_usr)