-4

how do I make this print 1,2,3,4 (I know I can make a loop and type print(loop) but I need it done in this specific way where the variable printed changes)

i1 = 1
i2 = 2
i3 = 3 
i4 = 4

for loop in range(4):
     print(i+loop)
Readraid
  • 33
  • 4
  • Does this answer your question? [Dynamically set local variable](https://stackoverflow.com/questions/8028708/dynamically-set-local-variable) – Brian Mar 12 '20 at 20:06
  • 1
    You're looking for a [`list`](https://docs.python.org/3/library/stdtypes.html#list) or a [`dict`](https://docs.python.org/3/tutorial/datastructures.html#dictionaries). – 0x5453 Mar 12 '20 at 20:06
  • Use a `list` or `dict`. – chepner Mar 12 '20 at 20:06
  • storing the values in a list and then looping with an post increment to have different outputs – FishingCode Mar 12 '20 at 20:07
  • Does this answer your question? [Dynamic variables in Python](https://stackoverflow.com/questions/15321886/dynamic-variables-in-python) – Chris Apr 02 '20 at 12:36

3 Answers3

0

You can't access variables that way. You can use a dictionary, though, to achieve the effect you're looking for:

d = {'i1': 1,
    'i2': 2,
    'i3': 3,
    'i4': 4}

for loop in range(1, 5):
    print(d[f'i{loop}'])
0

I would advise against ever doing this, but you could implement it this way:

i1 = 1
i2 = 2
i3 = 3 
i4 = 4

for loop in range(1,5):
     eval("i"+str(loop))
Mat-KH
  • 56
  • 3
  • thx so much. idk why people were disliking your post but this is really useful! – Readraid Mar 12 '20 at 20:24
  • @Readraid because using _**eval**_ is a [bad practice](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice). – Errol Mar 12 '20 at 20:37
0

You could loop through the variables:

for value in (i1,i2,i3,i4): print(value)
Alain T.
  • 34,859
  • 4
  • 30
  • 47