Pyt*_*nNB 1 python loops for-loop while-loop
我正在寻找使用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)
Run Code Online (Sandbox Code Playgroud)
正如你在最后看到的那样,我迷路了.理想情况下,我正在寻找输出
T0 = #
T1 = #
T... = #
T(Xpoly) = #
Run Code Online (Sandbox Code Playgroud)
有什么建议?
你可以在一个循环中完成所有事情
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
Run Code Online (Sandbox Code Playgroud)
以后你可以使用
print( terms['T0'] )
Run Code Online (Sandbox Code Playgroud)
但是使用列表而不是字典可能更好
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)
Run Code Online (Sandbox Code Playgroud)
以后你可以使用
print( terms[0] )
Run Code Online (Sandbox Code Playgroud)
甚至(获得前三个学期)
print( terms[0:3] )
Run Code Online (Sandbox Code Playgroud)