# 正整数校验函数
def is_positive_int(input_num):
# noinspection PyBroadException
# 上一条注释消除Pycharm 'Too broad exception clause' 警告
try:
positive_int = int(input_num)
if positive_int > 0:
return True
else:
return False
except Exception:
return False
# 打印商品列表函数
def print_list(__object):
# noinspection PyBroadException
# 上一条注释消除Pycharm 'Too broad exception clause' 警告
try:
for index in range(0, len(__object)):
print('%d\t%-10s\t%s' % (index + 1, __object[index][0], __object[index][1]))
except Exception:
return None
# 定义初始商品列表和购物车列表
product_list = [
['iPhone 12', 10000],
['iPhone 11', 6000],
['HUAWEI P30', 5000],
['荣耀 30', 4000],
['小米 10', 3000],
['红米 K40', 2000]
]
product_list_shopped = []
print('Welcome to shopping mall!')
# 输入购物预算,并校核预算是否合法
while True:
budget_input = input('您的购物预算是多少:')
if is_positive_int(budget_input):
budget = int(budget_input)
break
else:
print('输入有误,请重新输入.', end='')
# 首次打印商品列表
print('Product list:')
print_list(product_list)
# 进入购物程序
while len(product_list) > 0:
choice = input('选择购买商品编号[退出:quit]:')
if choice == 'quit':
break
# 校验输入的商品编号是否存在
elif is_positive_int(choice) and 0 int(choice) len(product_list) + 1:
product_index = int(choice) - 1
product_price = product_list[product_index][1]
# 余额判断购物是否成功
if budget > product_price:
budget = budget - product_price
product = product_list.pop(product_index)
product_list_shopped.append(product)
print('购买成功,购买了%s,花费%d,您的剩余预算为:%d' % (product[0], product_price, budget))
print_list(product_list)
elif budget == product_price:
budget = budget - product_price
product = product_list.pop(product_index)
product_list_shopped.append(product)
print('购买成功,您的预算已花完.')
break
else:
print('余额不足,请重新', end='')
else:
print('输入有误,请重新', end='')
# 购物车不为空时,打印购物列表和花费
if product_list_shopped:
sum_price = sum(x[1] for x in product_list_shopped)
print('您一共花费%d,购物清单如下:' % sum_price)
print_list(product_list_shopped)
print('欢迎下次光临!')