0

I am trying to loop similar variable names with different values but found unable to do so. I attached the code below. Could you advise me as to what to do by looping in order to get the effect of version 1 code? Many thanks.

#Version 1: The intended effect
def test():

    global v1, v2, v3

    v1 = 1
    v2 = 2
    v3 = 3

    print (v1)
    print (v2)
    print (v3)

if __name__ == "__main__":
    test()

And:

#Version 2: The loop I tried but failed
def test():

    global v1, v2, v3

    for i in range (1,3):
        "v" + str(i) = i
        print ("v" + str(i))

if __name__ == "__main__":
    test()
CL. L
  • 237
  • 1
  • 7
  • 22

1 Answers1

2
# Version 3: What you should be doing

def test():
    v = []
    for i in range(1, 3):
        v.append(i)
        print(v[i-1])

if __name__ == '__main__':
    test()

Global scope, "variable variables", and all sorts of other solutions are superfluous and generally ugly (because they will eventually cause hard-to-debug breakage in larger apps) for this. Just use a list for this type of thing.

# Version 4: Bonus list comprehension version

def test():
    return [i for i in range(1, 3)]   # or list(range(1, 3))
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
  • Hi all, thanks for the prompt reply. but what I am looking for is the loop through similar global variable. the main point is to do the part of "v" + str(i), printing is only for illustrating the results. As now I am writing a code to develop over 30 global variable in one series and every variable will be assigned to a tkinter widget with similar algorithm, therefore look for a way to so it with looping instead of repeating similar codes all the time. Any idea on this? thanks again. – CL. L Aug 15 '16 at 20:41
  • Why are you using global variables? You should almost never need global scope. (I can't think of any time in my professional career I have ever needed it.) Also, if you want to loop over these and they're all related (such that you might think to store them as `v1`, `v2`, ..., `vN`), then **that should tell you it ought to be a list**! – Two-Bit Alchemist Aug 15 '16 at 20:46