3

I am new to python. I am looking python version of the following shell code.

 for (( i=1; i <= 5; i++ ))
 do
       if avg_$i > 0 ; then
       print "Yes!!"
       fi
 done

I tried this :

    for i in range(1,5):
         if(avg_%d != 0) %(i) :
            print("Yes !! ")

It is obvious in other languages. I am sure python will also have an easy way to do it.

Grayrigel
  • 3,474
  • 5
  • 14
  • 32

1 Answers1

1

In Python you would use list arg instead of variables arg_1, arg_2, etc.

arg = [1, 4, -5, 15, -1]

for val in arg:
    if val > 0:
       print("yes")

So don't try to do it in the same way as in shell script.


If you really need with i then you would do

arg = [1, 4, -5, 15, -1]

for i in range(len(arg)):
    if arg[i] > 0:
       print("yes")

but version without range(len()) is better


Other method with i but without range(len())

arg = [1, 4, -5, 15, -1]

for i, val in enumerate(arg, 1):
    if val > 0:
       print("yes - element number", i)

EDIT: you can also keep it as dictionary

data = {
   'arg_1': 1, 
   'arg_2': 4, 
   'arg_3': -5, 
   'arg_4': 15,
   'arg_5': -1
}

for i in range(1, 6):
    if data['arg_{}'.format(i)] > 0:
       print("yes")
furas
  • 134,197
  • 12
  • 106
  • 148
  • That's sad. I had some specific reason to use multiple variables. It's obvious to append in list. I thought python will have some way to deal with that. anyway, thanks .. – Grayrigel Dec 31 '16 at 15:38
  • you can also use dictionary `data["arg_{}".format(i) ] > 0` but it makes no sense if you can use list. – furas Dec 31 '16 at 15:42
  • Yeah. I think I will use a list. Thanks !! – Grayrigel Dec 31 '16 at 15:44