I'm using the graphics.py lib and need to create a number of polygons based on how many the user wants (lets say 4).
I just need to know how create a unique name for each of these polygons such as polygon1, polygon2, polygon4, polygon5.
Thanks.
I'm using the graphics.py lib and need to create a number of polygons based on how many the user wants (lets say 4).
I just need to know how create a unique name for each of these polygons such as polygon1, polygon2, polygon4, polygon5.
Thanks.
If you really wanted to do this, you could:
for i in range(count):
new_poly = Polygon(whatever)
new_name = 'polygon{}'.format(i+1)
Then you have to store that new name and that new polygon somewhere. Maybe like this:
polygons = {}
for i in range(count):
new_poly = Polygon(whatever)
new_name = 'polygon{}'.format(i+1)
polygons[new_name] = new_poly
If you were thinking you'd rather just make each name a new variable… that's a bad idea. You don't want to dynamically create variables, because you want to keep data out of your variable names.
And really, there's no need for names here at all. This creates a list of count
polygons:
polygons = [Polygon(whatever) for _ in range(count)]
And now, if you need to access them by number, just do this:
polygons[2]
(although be aware that lists are 0-based, not 1-based).
Or, if you need to access all of them, you've got the whole list, so you don't have to keep writing (polygon1, polygon2, polygon3, polygon4)
everywhere; just polygons
.
You could handle it as a list
polygon = []
polygon.append(...)
And access them as
polygon[2]
Bad way:
You can use exec
.
for i in range(5):
exec("polygon%d = Polygon(something)"%i)
This is pretty safe, since i
if is only an integer. But using exec
is a really bad practice, since it very vulnerable. User can enter, or accidentally enter, a piece of code and mess up with your memory. So, unless you really have to do it, you shouldn't use it.
Also, if you are a fan of global variables, you can use this.
globals()["polygon%d"%i] = Polygon(something)
But using global vars too often isn't recommended either.
Nicer way
Alternatively, you can store it in a list, or a dictionary:
for i in range(5):
lst.append(Polygon(something_else)) #store it in a list
dict['polygon%d'%i] = Polygon(another_thing) #store it in a dict
Hope this helps!!