0

I have this variables:

time1 = end_time1 - start_time1
...
time2 = end_time2 - start_time2
...
time3 = end_time3 - start_time3
...
time4 = end_time4 - start_time4
...
time5 = end_time5 - start_time5

And I want to to this:

for i in range(5):
    print ("Search for " + str(i) + " element(s), has taken: " + "{0:.2f}".format(round(time,2)))

But, in format(round(time,2)) I want to use index 'i' from for to name the variable time like time1, time2, time3...

Any clue?

Bach
  • 6,145
  • 7
  • 36
  • 61
Zariweya
  • 295
  • 3
  • 13

2 Answers2

1

You can do that using locals():

for i in range(5):
    print ("Search for " + str(i) + " element(s), has taken: " + "{0:.2f}".format(round(locals()['time'+str(i+1)],2)))
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • Ok, this "worked". I mean, I used `globals()` but I got this same error: [Key Error](http://stackoverflow.com/questions/8857768/shelve-code-gives-keyerror). So I changed `globals()` to `locals()` and all went perfect. Thank you very much. – Zariweya May 08 '14 at 00:56
  • @Zariweya, Well glad to have been of a bit of help (kinda) – sshashank124 May 08 '14 at 00:58
1

You could put the time variables in a list (and really it probably would be advantageous to have the timeX variables as a list in the first place instead of separate variables).

times = [time1, time2, time3, time4, time5]

for i in range(5):
    print ("Search for " + str(i) + " element(s), has taken: " + \
           "{0:.2f}".format(round(times[i],2)))
Matt
  • 14,353
  • 5
  • 53
  • 65