python実現ショッピングカート
19915 ワード
個人はpythonを勉強していて、ネット上でいくつかの練習問題を探して、テーマの参考:フローチャートと参考コード:
作業要件:
1、プログラムを起動した後、登録、ログイン、終了を選択できる
2、登録を選択した後、ユーザー名とパスワードを入力して登録することができる
3、登録後に再度選択し、ログインして、ログインするたびに前回のログイン時間を提示する
4、退出を選択するとカートの履歴が印刷される(ショッピング時間、商品名、商品数)
5、ログインに3回失敗した場合にロックされる
6、チャージが可能
7、商品の種類3級を選んで購入する商品を選ぶ
8、操作の前に、終了または前のステップに戻ることができます.
参照コード:
black_list.json
database.json
goods.json
コード参照:
個人的にはショッピングの仕方がshopping()の中のコードは多すぎて、各級のコードを抽出することができて、みんなの参考に供して、転載して出典を明記してください
作業要件:
1、プログラムを起動した後、登録、ログイン、終了を選択できる
2、登録を選択した後、ユーザー名とパスワードを入力して登録することができる
3、登録後に再度選択し、ログインして、ログインするたびに前回のログイン時間を提示する
4、退出を選択するとカートの履歴が印刷される(ショッピング時間、商品名、商品数)
5、ログインに3回失敗した場合にロックされる
6、チャージが可能
7、商品の種類3級を選んで購入する商品を選ぶ
8、操作の前に、終了または前のステップに戻ることができます.
参照コード:
black_list.json
{
"terry": null
}
database.json
{
"lierl": {
"balance": 1502.0,
"last_login_time": "2018-04-01 09:34:01",
"pwd": "ec34a5f24bbbe82ad0d89ac656674316",
"register_time": "2018-04-01 08:36:07",
"shopping_list": [
{
"buy_time": "2018-04-01 08:00:10",
"goods_name": " ",
"goods_num": 3
},
{
"buy_time": "2018-04-01 09:34:28",
"goods_name": " ",
"goods_num": 2
}
]
}
}
goods.json
{
" ": {
" ": {
" ": 3999,
" ": 4299
},
" ": {
" ": 8999,
" ": 6000
},
" ": {
" ": 5099,
" ": 4599
}
},
"3C ": {
" ": {
" ": 6888,
"mac air": 8009
},
" ": {
" 5": 1999,
"iPhone6": 5299
}
},
" ": {
" ": {
"NIKE ": 899,
" ": 399
},
"T ": {
" ": 89,
" ": 75,
" ": 97
}
}
}
コード参照:
#!/usr/bin/env python3
# encoding:utf-8
'''
@author: lierl
@file: do_shopping_cart.py
@time: 2018/3/31 11:44
'''
import datetime
__author__ = 'lierl'
'''
1、 , , , ,
2、
3、 , , ,
4、 , ,
5、 , , , ,
6、 , , , ,
7、
shopping , , , 、 、
, enumerate, , , , enumerate , ,
os.system('clear'), ,
'''
import json
import re
import hashlib
'''
: Python Json json.dumps() str
: Json Python json.loads() dict,
:
database.json , , database.json, , ,
'''
welcome_info = '''
1. "A"
2. "B"
3. "Q"
'''
# json , database.json
def _load_database(filename = 'database.json'):
with open(file=filename, mode='r', encoding='utf-8') as f:
database = json.load(f)
return database#dict
# JSON , , , , ,
def _save_account(database, filename='database.json'):
# , ,
with open(file=filename, mode='w', encoding="utf-8") as f:
json.dump(database, f, indent=4, sort_keys=True, ensure_ascii=False)# dict
#
def _get_current_format_time():
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#
#
def _get_shopping_date(account):
database = _load_database()
return database[account]['shopping_time']
#
def _get_shopping_history(account):
database = _load_database()
account_data = database[account]#dict
history_shopping_list = account_data['shopping_list']#list
if len(history_shopping_list) > 0:#
for history_shopping_data in history_shopping_list:
buy_time = history_shopping_data['buy_time']#
goods_name = history_shopping_data['goods_name']#
goods_num = history_shopping_data['goods_num']#
print(" %s %s %s" % (buy_time, goods_num, goods_name))
else:
print(" 。。。")
# account=None , ,
# ,
def _logout(account_name = None):
if account_name is not None:
_get_shopping_history(account_name)
print(' , ')
exit()
#
def _get_balance(account_name):
database = _load_database()
return database[account_name]['balance']
#
def _shopping(account_name):
goods = _load_database(filename='goods.json')#
while True:
goods_first = {}
goods_first_index = []
for index, good in enumerate(goods, start=1):
goods_first[index] = good
goods_first_index.append(index)
print(' :%s :%s' % (index, good))
shopping_first_no = input(" ( b , q ):").strip()
if shopping_first_no.isdigit():
shopping_first_no = int(shopping_first_no)
if shopping_first_no in goods_first_index:
while True:
goods_name = goods_first[shopping_first_no]
print("%s :" % goods_name)
goods_seconds = {}
goods_seconds_index = []
for index,good in enumerate(goods[goods_name].keys(), start=1):
print(' :%s :%s' % (index, good))
goods_seconds_index.append(index)
goods_seconds[index] = good
shopping_second_no = input(" ( b , q ):").strip()
if shopping_second_no.isdigit():
shopping_second_no = int(shopping_second_no)
if shopping_second_no in goods_seconds_index:
while True:
goods_third_name = goods_seconds[shopping_second_no]
print(" %s" % goods_third_name)
final_goods_name = goods[goods_name][goods_third_name]
goods_final = {}
goods_final_index=[]
for index, good in enumerate(final_goods_name.keys(), start=1):
print('%s :%s %s :%s :%s' % (goods_third_name, index, goods_third_name, good,final_goods_name[good]))
goods_final[index] = good
goods_final_index.append(index)
goods_final_no = input(" %s ( b , q ):" % goods_third_name).strip()
if goods_final_no.isdigit():
goods_final_no = int(goods_final_no)
if goods_final_no in goods_final_index:
final_name = goods_final[goods_final_no]
buy_num = input(" %s :" % final_name).strip()
if buy_num.isdigit():
buy_num = int(buy_num)
database = _load_database()
account_balance = database[account_name]['balance']
goods_price = final_goods_name[final_name]
sum_amount = buy_num * goods_price
if account_balance >= sum_amount:
database[account_name]['balance'] = account_balance - sum_amount
shopping_list_data = {}
shopping_list_data['buy_time'] = _get_current_format_time()
shopping_list_data['goods_name'] = final_name
shopping_list_data['goods_num'] = buy_num
database[account_name]['shopping_list'].append(shopping_list_data)
d1 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') #
_save_account(database)# , :database.json
#
print(" %s %s %s" % (d1, buy_num, final_name))
else:
print(' , !')
return None
else:
print(" , ")
else:
print(" , ")
elif goods_final_no == 'q':
_logout(account_name)
elif goods_final_no == 'b':
break
else:
print(" , ")
else:
print(" , ")
elif shopping_second_no == 'q':
_logout(account_name)
elif shopping_second_no == 'b':
print(" ?")
break
else:
print(" , ")
else:
print(" , ")
elif shopping_first_no == 'q':
_logout(account_name)
elif shopping_first_no == 'b':
return
else:
print(" , ")
#
def _recharge(account_name):
database = _load_database()
print(" :%.2f " % _get_balance(account_name))
while True:
input_data = input(" ... ( b , q ):").strip()
if re.match(pattern=r'^\d+.\d{1,2}$', string=input_data):
# , ,
if input_data.isdigit():#
amount = int(input_data)
else:#
amount = float(input_data)
database[account_name]['balance'] += amount
_save_account(database)
#
curr_balance = _get_balance(account_name)
print(' , \033[32m%.2f\033[0m ' % curr_balance)
break
elif input_data == 'b':
break
elif input_data == 'q':
_logout(account_name)
else:
print(" , ")
#
def _login():
account_name = input(" ( q ):").strip()
if account_name == 'q':
_logout()
else:
#
black_data_list = _load_database('black_list.json')
black_user_list = []#
for black_user in black_data_list.keys():
black_user_list.append(black_user)
#
if account_name not in black_user_list:
# ,
current_data_list = _load_database()
current_user_list = []
for current_user in current_data_list.keys():
current_user_list.append(current_user)
if account_name in current_user_list:
loginTimes = 1#
#
current_user_passwd = current_data_list[account_name]['pwd']#
while loginTimes <= 3:
input_passwd = input(" :").strip()
if _get_md5(input_passwd) == current_user_passwd:
# ,
last_login_time = current_data_list[account_name]['last_login_time']
if last_login_time is not None:
print(" , :%s" % last_login_time)
else:
print(" , ")
current_data_list[account_name]['last_login_time'] = _get_current_format_time()
_save_account(current_data_list)
#
account_balance = current_data_list[account_name]['balance']#
#
print(' \033[32m%.2f\033[0m' % account_balance)
while True:
#
print("*"*60)
print(" :")
print("h: ")
print("s: ")
print("t: ")
print("q: ")
print("*" * 20)
command = input(" :").strip()
if command == 'h':#
_get_shopping_history(account_name)
elif command == 't':#
_recharge(account_name)
elif command == 's':# , shopping_list shopping_time
# _clear_shopping_cart(account_name)
_shopping(account_name) #
elif command == 'q':
_logout(account_name)
else:
# ,
print(' , !')
else:
# , ,
if loginTimes == 3: #
print(" , , , ")
# black_list.json
black_data_list[account_name] = None
# black_data_list.setdefault(account_name)
#
_save_account(database=black_data_list, filename='black_list.json')
_logout()#
else:
print(" , , %s " % (3 - loginTimes))
loginTimes += 1
else:
#
print(' , ! b , q, !')
print('-----------------------------------------------------')
else:# ,
print(" , ")
_logout()#
def _get_md5(str):
h1 = hashlib.md5()
h1.update(str.encode('utf-8'))
return h1.hexdigest()
#
def _add_user():
while True:
account_name = input(" :").strip()
if account_name is not '':
while True:
account_pwd = input(" :").strip()
if account_pwd is not '':
#
database = _load_database()
account_data_dict = {}
account_data_dict['shopping_list'] = []
account_data_dict['pwd'] = _get_md5(account_pwd)
account_data_dict['balance'] = 0.0
account_data_dict['last_login_time'] = None
account_data_dict['register_time'] = _get_current_format_time()
database[account_name] = account_data_dict
_save_account(database)
print(" , ")
break
else:
print(" , ")
break
else:
print(" , ")
def main():
while True:
#
'''
1. "A"
2. "B"
3. "Q"
'''
print("*"*60)
print(" ".rjust(10, ' '))
print(" :".rjust(12, ' '))
print("A: ".rjust(6,' '))
print("B: ".rjust(6,' '))
print("Q: ".rjust(6,' '))
print("*"*60)
command = input(" :").strip()#
command = command.upper()
if command == 'A':#
_add_user()
elif command == 'B':#
_login()
elif command == 'Q':#
_logout()
else:#
print(" , ")
if __name__ == '__main__':
main()
************************************************************
:
A:
B:
Q:
************************************************************
:a
:test
:test
,
************************************************************
:
A:
B:
Q:
************************************************************
:b
( q ):test
:test
,
0.00
************************************************************
:
h:
s:
t:
q:
********************
:t
:0.00
... ( b , q ):10000
, 10000.00
************************************************************
:
h:
s:
t:
q:
********************
:s
:1 :3C
:2 :
:3 :
( b , q ):1
3C :
:1 :
:2 :
( b , q ):2
:1 :mac air :8009
:2 : :6888
( b , q ):b
3C :
:1 :
:2 :
( b , q ):1
:1 :iPhone6 :5299
:2 : 5 :1999
( b , q ):1
iPhone6 :1
2018-04-01 09:50:35 1 iPhone6
************************************************************
:
h:
s:
t:
q:
********************
:s
:1 :3C
:2 :
:3 :
( b , q ):3
:
:1 :T
:2 :
( b , q ):1
T
T :1 T : :75
T :2 T : :97
T :3 T : :89
T ( b , q ):1
:10
2018-04-01 09:50:56 10
************************************************************
:
h:
s:
t:
q:
********************
:q
2018-04-01 09:50:35 1 iPhone6
2018-04-01 09:50:56 10
,
個人的にはショッピングの仕方がshopping()の中のコードは多すぎて、各級のコードを抽出することができて、みんなの参考に供して、転載して出典を明記してください