Search code examples
pythonvariablesinputarithmetic-expressions

Repeating an input multiple times based on variable


So I'm new to python and having a complete mental block as to how I can elegantly repeat this input for the product name based on the value of num_qc.

So for example if num_qc = 4 I would want the user to enter nam_prod1, nam_prod2 etc... As far as my understanding goes, I wouldnt want to pre-define these variables as the user could only enter 1 for num_qc or 50?

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

Solution

  • you have to use a for loop or another loop cycle , what you want is:

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

    the name_prod variable will be overwritten with each cycle, you can use a 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)))