Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm looking to use a for loop to create multiple variables, named on the iteration (i), and assign each one a unique int.

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


terms={}
for i in range(0, Xpoly):
    terms["Term{0}".format(i)]="PH"

VarsN = int(len(terms))
for i in range(VarsN):
    v = str(i)
    Temp = "T" + v
    Var = int(input("Enter the coefficient for variable"))
    Temp = int(Var)

As you see at the end I got lost. Ideally I'm looking for an output where

T0 = #
T1 = #
T... = #
T(Xpoly) = #

Any Suggestions?

like image 991
PythonNB Avatar asked May 23 '26 00:05

PythonNB


1 Answers

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] )
like image 98
furas Avatar answered May 24 '26 18:05

furas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!