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

标签 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)

正如你在最后看到的,我迷路了。理想情况下,我正在寻找输出

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] )

甚至(获得前三项)

 print( terms[0:3] )

关于python - 使用循环创建和分配多个变量 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41645898/

相关文章:

python - 如何在 python 列表中添加 kg 或 grams 'superficially ' 等单位

python - 在 Python 中使用 Gspread 共享给多个用户

javascript - 在 AngularJS 中创建动态 ng-model

c - 阅读列表

javascript - JQuery for 循环和数组 - 为什么这个变量未定义?

javascript - 使用for循环检查所有元素是否满足条件

Java 增强的 For 循环

python - 如何在 block 文件中写入列表列表

python - 从理解中消除理解中的冗余函数调用

r - 在列中循环 - 仅使用条件一次