如何接受用户输入的多个参数并将其传递给参数并打印所有项目

时间:2019-12-11 11:23:37

标签: python python-3.x function

  • 该函数接受用户购物清单的多个参数并打印用户从市场购买的所有商品,但我将一个清单作为参数传递给它,该清单显示的不是单个商品:

  • (使用任意参数概念提供解决方案)

以下是一些代码:

def customer_shopping(*shopping_list):
    print("\n--------- Shopping List --------")    
    for element in shopping_list:
        print("You bought: ",element)

shopping_list = []

while True:
    items = input("\nEnter the item you bought from market \nIf you leave enter'quit': ")
    if items == 'quit':
        break
    shopping_list.append(items)

customer_shopping(shopping_list)

2 个答案:

答案 0 :(得分:1)

从函数定义中删除解包运算符*并调用:

def customer_shopping(shopping_list):
...
customer_shopping(shopping_list)

这给出了输出:

Enter the item you bought from market 
If you leave enter'quit': banana


Enter the item you bought from market 
If you leave enter'quit': carrot


Enter the item you bought from market 
If you leave enter'quit': quit

--------- Shopping List --------
You bought: Banana
You bought: Carrot

答案 1 :(得分:0)

问题是:

def customer_shopping(*shopping_list):

如果您只是删除*,它将完全按照您的要求打印!