【问题标题】:Repeating an input multiple times based on variable根据变量重复输入多次
【发布时间】:2019-02-21 06:51:40
【问题描述】:

所以我是 python 新手,并且对于如何根据 num_qc 的值​​优雅地为产品名称重复此输入有一个完整的心理障碍。

例如,如果 num_qc = 4 我希望用户输入 nam_prod1、nam_prod2 等... 据我了解,我不想预先定义这些变量,因为用户只能为 num_qc 或 50 输入 1?

#report info
num_qc = input('Total QC open: ')
nam_prod = num_qc  * input('Name of unit %s: ' % num_qc)

【问题讨论】:

标签: python variables input arithmetic-expressions


【解决方案1】:

您必须使用 for 循环或另一个 loop cycle , 你想要的是:

num_qc = int(input('Total QC open: '))
for x in range(0,num_qc):
    nam_prod = input('Name of unit %s: ' % (x+1))

name_prod 变量将在每个循环中被覆盖, 你可以使用list:

num_qc = int(input('Total QC open: '))
nam_prod = []
for x in range(0,num_qc):
        nam_prod.append(input('Name of unit %s: ' % (x+1)))

【讨论】:

  • 我需要保留每个变量,以便第二个代码块保留该变量?我打算在程序结束时将此信息写入txt文件或excel
  • 当然,每个数据在列表中都有自己的索引,您可以使用它来读取它(例如 nam_prod[0]、nam_prod[1]、nam_prod[2]、...。 ) 你可以使用循环循环读取所有列表。查看链接以了解有关列表的更多信息docs.python.org/3/tutorial/datastructures.html
  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2018-10-20
相关资源
最近更新 更多