这篇文章给大家分享的是用python实现文字版购物车功能的介绍。实现需求,效果及代码如下,是比较简易的效果,对大家学习和理解购物车功能的实现有一定的价值,因此分享给大家做个参考,文中示例代码介绍的非常详细,感兴趣的朋友接下来一起跟随小编看看吧。
实现代码如下:
# 正整数校验函数
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('欢迎下次光临!')

预算输入限制为正整数,其余输入均会提示并要求重新输入
预算校验可新增:





关于用python实现文字版购物车功能的方法及代码就分享到这,本文只是提供了一种实现思路,代码仅供参考,需要的朋友可以了解看看,希望对大家学习python有帮助,想要了解更多可以继续浏览群英网络其他相关的文章。
文本转载自脚本之家
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理