用python怎样实现文字版购物车功能?
Admin 2021-12-11 群英技术资讯 860 次浏览
这篇文章给大家分享的是用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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
在我们日常生活中,我们可以通过求集合的交集,得出重复的部分,去解决去重的问题。 python作为很好用的编程工具,是可以帮助我们解决数学问题的。本文介绍python中实现集合交集的三种方法,即使用使用&计算、使用python推导式计算和使用python集合的内置方法计算。
python中递归函数怎样使用?很多新手在使用递归函数时,会出现多种问题,对此,这篇文章就给大家分享一下python中递归函数的用法以及要注意的一些问题,有需要的朋友可以参考。
由于列表是序列的一种,列表支持我们对字符串序列进行操作。唯一的区别就是其结果往往是列表而不是符串。我们都知道列表方便我们理解操作,是我们在日常生活中解决问题的方法之一。
bool() 函数用于将给定参数转换为布尔类型,如果没有参数,返回 False。 bool 是 int 的子类。
程序要实现人机交互功能,需能够向显示设备输出有关信息及提示,同时也要能够接收从键盘输入的数据。Python提供了用于实现输入/输出功能的函数input0和print0,下面分别对这两个函数进行介绍。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008