【问题标题】:How do you store two different inputs from the same variable?你如何存储来自同一个变量的两个不同的输入?
【发布时间】:2017-03-21 03:49:35
【问题描述】:
    while n == 1:
        w = input("Input the product code: ")   

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

【问题讨论】:

  • 改为使用w 的列表并仅附加每个条目?
  • 您在输入输入时不能打印它吗?此外,您可以在变量中存储 2 个不同的东西的唯一方法是它是一个集合、一个类或某种容器,除非您将您的值连接在一起并将其存储到字符串中,但这会变得混乱且开销太大。跨度>

标签: python


【解决方案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的值。

【讨论】:

  • 哦,这就是它的工作原理
  • @Anya 是的。尽管请记住,列表不是容器类型的唯一选择。我建议阅读up on Python container types
【解决方案2】:
inputs = []
for i in range(expected_number_of_inputs):
    inputs.append(input('Product Code: '))
for i in inputs:
    print(i)

【讨论】:

    【解决方案3】:

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

    方案一:使用两个变量

    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])
    

    【讨论】:

    • 您的解决方案 2 将提供 IndexError。使用w.append(input())
    猜你喜欢
    • 2022-11-02
    • 1970-01-01
    • 2022-11-23
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多