Using a loop to create and assign multiple variabl

2020-01-27 08:22发布

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?

1条回答
时光不老,我们不散
2楼-- · 2020-01-27 08:57

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] )
查看更多
登录 后发表回答