我正在寻找使用for循环来创建多个变量,在迭代(i)上命名,并为每个变量分配一个唯一的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)
正如你在最后看到的那样,我迷路了。理想情况下,我正在寻找输出
T0 = #
T1 = #
T... = #
T(Xpoly) = #
任何建议?
答案 0 :(得分:6)
你可以在一个循环中完成所有事情
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
稍后你可以使用
print( terms['T0'] )
但是使用列表而不是字典可能更好
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)
稍后你可以使用
print( terms[0] )
甚至(获得前三个学期)
print( terms[0:3] )