Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用循环创建和分配多个变量(Python)_Python_Loops_For Loop_While Loop - Fatal编程技术网

使用循环创建和分配多个变量(Python)

使用循环创建和分配多个变量(Python),python,loops,for-loop,while-loop,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 = "

我希望使用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) = #

有什么建议吗?

您可以在一个循环中完成所有操作

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] )
甚至(获得前三个任期)


改用字典变量
T0
T1
。CodeTemp=“T”+v不创建名为T0T1的变量,而只创建文本“T0”“T1”,您可以在字典术语[Temp]=Var中使用小写变量和函数名-变量名,Temp
var
-它使代码更具可读性,因为我们只为类使用
CamelCase
名称。您可以为
循环使用一个
,使用
术语[“Term{0}”。format(i)]=var
,以防任何人来到这里,并希望实现作者所描述的内容。使用Do
range(多少+1)
。这就是我从他的问题中理解的<代码>范围(0,Xpoly)
他想要
T(Xpoly)
。也许
T(Xpoly)
建议
多少+1
,但是
范围(0,Xpoly)
只意味着
多少
-从
0
多少-1
(从
0
Xpoly-1
 print( terms[0:3] )