0

I am trying to create a number of variables that I can use based on the input to a function function(n), so I have n variables, all titled x1, x2,...,xn. As well, could I call the variables with like a loop with something almost like

for i in range(1,n+1):
    print(xi)

this is what I tried

def createVar(n):
    var='x'+str(n)
    Vars=globals()
    Vars[var]=0
K0PSTL
  • 1
  • 2
    Consider using a `list` or `dict` instead. A variable number of named variables can be problematic because whatever uses these variables later would have to know their names. You may just be creating more problems for yourself down the road. – tdelaney Jun 13 '23 at 20:47
  • `createVar` worked. Is the for loop the problem? You could get them from `globals()` just like you set them. – tdelaney Jun 13 '23 at 20:50
  • Your loop cannot print the values of global variables created by your function - it will just look for a variable named `xi`. This is all a minefield of potential confusion - it;s good advice as already commented to use an alternative data structure. – user19077881 Jun 13 '23 at 21:14

0 Answers0