Aaron Perry
Aaron Perry

Reputation: 1041

Define Multiple Variables In While Loop

I need to define multiple variables within a while loop to be called inside of the while loop in Python.

Code:

tau = 0

while tau < 10:

(tau)

   d_abrv = "d" % tau
   day = "day" % tau

d_abrv = datetime.now() + timedelta(days=tau)
day = d_abrv.strftime('%a %d-%b-%y')
image_date = d_abrv.strftime('%Y%m%d')

plt.savefig(homedir + "/out/_tmax_" + d_abrv + "_ne.png", dpi = 300)

tau = tau + 1

sys.exit()

What am I doing wrong?

Ideally, I need to define a variable that loops through number 0 through 10. After, I need to be able to use this defined variable throughout the script, including defining new variables with the variable, e.g., tau=0, change day0 to day=day+tau

Upvotes: 0

Views: 164

Answers (2)

Johannes Hinrichs
Johannes Hinrichs

Reputation: 163

If I correctly understood your problem, you want to create a new variable in every iteration of the loop. I have done this successfully in the past by using exec(). I am still uncertain whether this is a pythonic thing to do, but it worked. Based on your previous comments, I would suggest the following code:

tau = 0
timeformat = "'%a %d-%b-%y'"
timeformat2 = "'%Y%m%d'"

while tau < 10:

  exec("d%d = datetime.now() + timedelta(days=tau)" % tau)
  exec("day%d = d%d.strftime(%s)" % (tau,tau,timeformat))
  exec("image_date = d%d.strftime(%s)" % (tau,timeformat2))

  exec("plt.savefig(homedir + '/out/_tmax_' + day%d + '_ne.png', dpi = 300)" % tau)

  tau = tau + 1

sys.exit()

I tested this code (on some dummy data i plotted) and I successfully get the plots saved with filenames "_tmax_Fri 09-Oct-15_ne.png" etc.

The rest of your code would have the variables day0, day1, etc. available for use.

Upvotes: -1

scrineym
scrineym

Reputation: 759

Not entirely sure what you mean, but would this suffice?

from datetime import datetime
from datetime import timedelta


for tau in range(0,10):
   d_abrv = "d" + str(tau)
   day = "day" +str(tau)
   d_abrv = (datetime.now() + timedelta(days=tau))
   day = d_abrv.strftime('%a %d-%b-%y')
   image_date = d_abrv.strftime('%Y%m%d')
   plt.savefig(homedir + "/out/_tmax_" + d_abrv + "_ne.png", dpi = 300)

sys.exit()

although I must say I'm not sure what this means:

plt.savefig(homedir + "/out/_tmax_" + d_abrv + "_ne.png", dpi = 300)

Upvotes: 3

Related Questions