Python列表练习题

时间:2023-02-24 10:37:04

实现功能:

列表为:['Iphone8',6888],['MacPro',14800],['小米6',2499],['Coffee',31],['Book',80],['Nike Shoes',799]

实现一个类似购物车的语句,用户循环输入编号可以将列表内的商品储存到一个新的列表里面,当用户输入'q'时退出循环

实现代码如下:

products = [['Iphone8',6888],['MacPro',14800],['小米6',2499],['Coffee',31],['Book',80],['Nike Shoes',799]]
shopping_cart = []
while True:
print ('-------------商品列表--------------')
for index,i in enumerate(products):
print ('%s.%s %s'%(index,i[0],i[1]))
choice = input('please input your numbers:')
if choice.isdigit():
choice = int(choice)
shopping_cart.append(products[choice])
elif choice == 'q':
print ('-----------------您以购买如下商品------------')
for index,i in enumerate(shopping_cart):
print ('%s.%s %s'%(index,i[0],i[1]))
break

同时可以添加一个标志位,当用户输入'q'的时候标志位改变while的判断条件,使循环退出

具体代码如下:

products = [['Iphone8',6888],['MacPro',14800],['小米6',2499],['Coffee',31],['Book',80],['Nike Shoes',799]]shopping_cart = []run_flag = Truewhile run_flag:    print ('-------------商品列表--------------')    for index,i in enumerate(products):        print ('%s.%s %s'%(index,i[0],i[1]))    choice = input('please input your numbers:')    if choice.isdigit():        choice = int(choice)        shopping_cart.append(products[choice])    elif choice == 'q':        print ('-----------------您以购买如下商品------------')        for index,i in enumerate(shopping_cart):            print ('%s.%s %s'%(index,i[0],i[1]))        run_flag = False