Using a loop to create and assign multiple variables (Python) [duplicate]

You can do everything in one loop

how_many = int(input("How many terms are in the equation?"))

terms = {}

for i in range(how_many):
    var = int(input("Enter the coefficient for variable"))
    terms["T{}".format(i)] = var 

And later you can use

 print( terms['T0'] )

But it is probably better to a use list rather than a dictionary

how_many = int(input("How many terms are in the equation?"))

terms = [] # empty list

for i in range(how_many):
    var = int(input("Enter the coefficient for variable"))
    terms.append(var)

And later you can use

 print( terms[0] )

or even (to get first three terms)

 print( terms[0:3] )

Leave a Comment