如何存储来自同一变量的两个不同输入?

时间:2016-10-14 19:57:30

标签: python

    while n == 1:
        w = input("Input the product code: ")   

问题是当输入w的新代码时,w被覆盖。例如,如果w = 24,那么w = 54,如果你打印(w)它将只打印54,因为它是最新的输入。你怎么做它打印w的所有输入?

3 个答案:

答案 0 :(得分:1)

inputs = []
for i in range(expected_number_of_inputs):
    inputs.append(input('Product Code: '))
for i in inputs:
    print(i)

答案 1 :(得分:1)

使用容器类型而不是单个变量。在这种情况下,list()似乎是合适的:

inputs = [] # use a list to add each input value to
while n == 1:
    inputs.append(input("Input the product code: ")) # each time the user inputs a string, added it to the inputs list
for i in inputs: # for each item in the inputs list
    print(i) # print the item

注意:以上代码无法编译。您需要填写变量n的值。

答案 2 :(得分:0)

您可以通过两种不同的方式执行此操作,但您尝试执行此操作的方式将无效。你不能让一个不是列表的变量保存两个值。

解决方案1:使用两个变量

w1 = input("value1")
w2 = input("value2")
print(w1)
print(w2)

解决方案2:使用列表

w = []
w.append(input("value1"))
w.append(input("value2"))
print(w[0])
print(w[1])