3

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?

PythonNB
  • 33
  • 1
  • 1
  • 3
  • 2
    use dictionary instead variables `T0`, `T1` . Code `Temp = "T" + v` doesn't create variable with name `T0`, `T1` but only text `"T0"`, `"T1"` which you can use in dictionary `terms[Temp] = Var` – furas Jan 14 '17 at 01:38
  • 1
    BTW: use `lower_case` names for variables and functions - `vars_n` , `temp`, `var` - it makes code more readable because we use `CamelCase` names only for classes. – furas Jan 14 '17 at 01:39
  • 1
    you can use one `for` loop - with `terms["Term{0}".format(i)] = var` – furas Jan 14 '17 at 01:42
  • In case anyone lands here and wants to implement exactly what's described by the author use [this](https://tio.run/##VU7LCsIwELznKxY8bNKWUvUiQv5EkKhbDaTZsImVfn1tRQ/OaWZgHmkqD477Q5J59kNiKcBZ9ZYTRY2jk1xYqE0TNujQKGcRVc8CHnwEcfFOumu2XWeOCha42uJ4xjoX0d7UaL@0qnaLOsUl3L7EF9Kr7YxZ9DVwJm3UjQI41QsP8BuG76dKcW6FBh7p/5VRm08dDM9QfAq0Rr27BMrz/AY) – the sigmoid infinity Oct 28 '20 at 15:22

1 Answers1

8

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] )
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
furas
  • 134,197
  • 12
  • 106
  • 148
  • Do `range(how_many+1)`. That is what I understood from his question. `range(0, Xpoly)` and he wants `T(Xpoly)`. – Mohammad Yusuf Jan 14 '17 at 02:01
  • Maybe `T(Xpoly)` suggest `how_many+1` but `range(0, Xpoly)` means only `how_many` - from `0` to `how_many-1` (from `0` to `Xpoly-1`) – furas Jan 14 '17 at 02:08