【Python小练习】购物车小程序

支持购物车物品增删改查小demo!

'''
-*- coding: utf-8 -*-
@Author  : Qixi
@Time    : 2022/2/13 14:30
@File    : shoppingcar.py
'''
from IPython.display import clear_output
# 使用列表创建购物车
cart = []

# 展示购物车
def showCart():
    clear_output()
    if cart:
        print('What\'s in the cart:'.format())
        for item in cart:
            print('- {}'.format(item))
    else:
        print('Your cart is empty now!')

# 添加物品
def addItem(item):
    clear_output()
    cart.append(item)
    print('{} has been added'.format(item))
# 删除物品
def removeItem(item):
    clear_output()
    try:
        cart.remove(item)
        print("{} has been removed".format(item))
    except:
        print("Sorry we could not remove that item!")
# 清空购物车
def clearCart():
    clear_output()
    cart.clear()
    print('Your cart is empty now!')
# 创建主函数
def main():
    while True:
        userInput = input("quit/add/remove/show/clear: ").lower() #购物功能,统一输入成小写!
        if userInput == "quit":
            print("Bye!")
            break
        if userInput == "show":
            showCart()
        elif userInput =="add":
            item = input("What would you like to add?").title()
            addItem(item)
        elif userInput == "remove":
             item = input("What would you like to remove?").title()
             removeItem(item)
        elif userInput == "clear":
             clearCart()
        else:
            print("Wrong!")

if __name__ == '__main__':
    main() # 运行程序

运行结果:

quit/add/remove/show/clear: add
What would you like to add?apples
Apples has been added
quit/add/remove/show/clear: show
What's in the cart:
- Apples
quit/add/remove/show/clear: quit
Bye!

猜你喜欢

转载自blog.csdn.net/weixin_54430466/article/details/122909199