0

I have

x={}

if zone1 == 1:
   x['zone1_val'] = zone1_test - 10
   ....

if zone2 == 1:
   x['zone2_val'] = zone2_test - 10
   .....

if zone3 == 1:
   x['zone3_val'] = zone3_test - 10
   .....

How can create a for loop and do this thing something like below.

x={}
for i in range(1,4):
    if zone{i} == 1:
        x['zone{i}_val'] = zone{i}_test - 10
Santhosh
  • 9,965
  • 20
  • 103
  • 243
  • `locals()` and `globals()` exist, but you should probably avoid them in favor of simply not having separate variables in the first place. Or at least putting them into an object so you can use `vars`, `setattr`, `getattr`, etc. – o11c Jul 09 '21 at 23:10
  • 2
    Instead of separate variables, you should have two lists `zone` and `zone_test`. – chepner Jul 09 '21 at 23:11
  • 2
    You don't. You use a list or a dictionary instead of having numbered variables. –  Jul 09 '21 at 23:11
  • these are database columns. So i dont have much choice – Santhosh Jul 09 '21 at 23:18
  • It's hard to see how these being database columns forces you into a bad naming/data pattern. Is the database generating the python? – Mark Jul 09 '21 at 23:24
  • I think if anything I'm curious how these variables are being set. If they are indeed coming from a database, then all the more it would make sense to put them into an object or `dict`. Please provide us with how these variables are being set. – Ben Y Jul 09 '21 at 23:52
  • I have a django model with fileds `zone1, zone2` etc. So i get them from `modelinstance.zone1` like that. Infact I have to check `if modelinstance.zone1 == 1:` So how to get them through dict here – Santhosh Jul 09 '21 at 23:57
  • 1
    With objects, one way is to use [getattr](https://docs.python.org/3/library/functions.html#getattr). To get something like `modelinstance.zone1 ` with variable zone attributes: `getattr(modelinstance, f"zone{i}")` There are also various ways to convert the Django models to dicts...[see also](https://stackoverflow.com/questions/21925671/convert-django-model-object-to-dict-with-all-of-the-fields-intact) – Mark Jul 10 '21 at 00:24

1 Answers1

-1

You probably need to set the variable name as a string and use eval to attempt to evaluate it. If the variable doesn't exist, you'll get an error.

x={}
for i in range(1,4):
    varname = "zone{}".format(i)  # or f"zone{i}"
    testvar = varname + '_test'
    if eval(varname) == 1:
        x[varname + '_val'] = eval(testvar) - 10

Edit: Although the question has already been closed, my intent was to answer the OP's question as thoroughly as I could. I would have used a dict as others have commented, but that is probably a latter stage in any developer's refinement of their craft.

Ben Y
  • 913
  • 6
  • 18