支持购物车物品增删改查小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!
|