bionboy bionboy - 17 days ago 5
Python Question

How to set multiple variables with a loop using python

I am relatively new to the Python language and was wondering if there was a more efficient way of declaring multiple variables. I am declaring a lot of random numbers in order to make randomly placed and color triangles.

from time import sleep
from graphics import *
from random import randint

def main():
win = GraphWin("Wow!", 500, 500)
win.setBackground("black")
for i in range(1,100):
rand = randint(0,500)
rand1 = randint(0,500)
rand2 = randint(0,500)
rand3 = randint(0,500)
rand4 = randint(0,500)
rand5 = randint(0,500)
randR = randint(0,255)
randG = randint(0,255)
randB = randint(0,255)
p = Polygon(Point(rand,rand1), Point(rand2,rand3), Point(rand4,rand5)).draw(win)
p.setFill(color_rgb(randR, randG, randB))
Circle(Point(100,100), i).draw(win).setFill('blue')
if i > 60:
Circle(Point(200,400), (i-50)).draw(win).setFill('red')
if i > 30:
Circle(Point(400,130), (i-30)).draw(win).setFill('green')
time.sleep(.03)
win.getMouse()
win.close()

main()


The variables in question are all of the random number variables (rand).

I would also be interested to know how this could be done in other languages or if there is a common method that is cross-language.

Answer

Use lists:

rand_nums = [randint(0, 500) for i in range(6)] # 6 random numbers
rand_rgb = [randint(0, 255) for i in range(3)] # 3 random rgb-range numbers
p = Polygon(Point(rand_nums[0], rand_nums[1]), Point(rand_nums[2], rand_nums[3]), Point(rand_nums[4], rand_nums[5])).draw(win)
...

and so on.