如何将不同的输入存储在单个变量中并打印出来?

时间:2019-04-22 16:11:49

标签: python-3.x

到目前为止,代码可以正常工作并要求提供我需要的所有内容,但它会不断输出最后一个输入,而不是最后的所有3个。我知道为什么,但不知道如何解决。任何帮助表示赞赏。

我尝试做3个单独的功能,但使它变得凌乱,无法正常工作。

class RetailItem:

    def __items__(s,d,p):
            return s,d,p
    def main():
        for x in range (3):
            s = input("What is item name: ")
            d = int(input("How many of these items are in stock? "))
            p = float(input("How much is each unit price? "))
        for __items__ in range(3):
            print("Description:", s)
            print("Units:", d)
            print("Price:", p)
    main()

现在,代码执行此操作。

What is item name: 1
How many of these items are in stock? 1
How much is each unit price? 1
What is item name: 2
How many of these items are in stock? 2
How much is each unit price? 2
What is item name: 3
How many of these items are in stock? 3
How much is each unit price? 3
Description: 3
Units 3
Price 3.0
Description: 3
Units 3
Price 3.0
Description: 3
Units 3
Price 3.0
最后,

我要阅读它。

Description: 1
Units 1
Price 1
Description: 2
Units 2
Price 2
Description: 3
Units 3
Price 3

2 个答案:

答案 0 :(得分:0)

在循环的每次迭代中,您将覆盖变量保存的先前值。

这对于您的目标而言可能过于复杂,但是您可以将字典作为数据结构嵌套在列表中。

示例:

#initialize an empty list and dict
myList = []
myDict = {}
def main():
    for x in range (3):
        #each loop overrides the dict
        myDict["description"] = input("What is item name: ")
        myDict["units"] = int(input("How many of these items are in stock? "))
        myDict["price"] = float(input("How much is each unit price? "))
        #append a copy of dict to our list
        myList.append(myDict.copy())
    #loop through list and unpack values from dictionaries
    for item in myList:
        for key, value in item.items():
            print(key.capitalize() + ":" + str(value))

main()

输入:

What is item name: 1
How many of these items are in stock? 1
How much is each unit price? 1
What is item name: 2
How many of these items are in stock? 2
How much is each unit price? 2
What is item name: 3
How many of these items are in stock? 3
How much is each unit price? 3

输出:

Description:1
Units:1
Price:1.0
Description:2
Units:2
Price:2.0
Description:3
Units:3
Price:3.0

也许有一种更简单的方法来完成您要完成的任务,但是这样您就可以跟踪输入信息,祝您好运。

答案 1 :(得分:0)

s,d,p = [],[],[]
for x in range(3):
        s.append(input("What is item name: "))
        d.append(int(input("How many of these items are in stock? ")))
        p.append(float(input("How much is each unit price? ")))
for i in range(3):
        print("Description:", s[i])
        print("Units:", d[i])
        print("Price:", p[i])

其他可能性是创建一个数组:

array = [[],[],[]]
for x in range(3):
        array[0].append(input("What is item name: "))
        array[1].append(int(input("How many of these items are in stock? ")))
        array[2].append(float(input("How much is each unit price? ")))
for i in range(3):
        print("Description:", array[0][i])
        print("Units:", array[1][i])
        print("Price:", array[2][i])