-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
  • 41
  • 4

3 Answers3

1

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
  • 76
  • 4
  • 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 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

You could loop through the variables:

for value in (i1,i2,i3,i4): print(value)
Alain T.
  • 40,517
  • 4
  • 31
  • 51