Basic Python: Passing a string as an input to a function
<p>I am just starting off with python. I have 4 variables F_1, F_2, F_3 and F_4. Each containing a matrix in them. I want to count the non-zero values in each of them. So i wrote a loop.</p>

<pre><code>f_1 = thresh1[1:mr, 1:mc]
f_2 = thresh1[1:mr, (mc+1):width]
f_3  = thresh1[(mr+1):height, 1:mc]
f_4 = thresh1[(mr+1):height, (mc+1):width]

b_1 = thresh2[1:mr, 1:mc]
b_2 = thresh2[1:mr, (mc+1):width]
b_3  = thresh2[(mr+1):height, 1:mc]
b_4 = thresh2[(mr+1):height, (mc+1):width]

for i in range(1, 5):
    n1 = "f_"
    n2 = "b_"
    num = str(i)
    n1 += num
    n2 += num

    r = cv2.countNonZero((n1)/cv2.countNonZero(n2))
    print r
</code></pre>

<p>I want to pass the concatenated strings <code>n1</code> and <code>n2</code> as inputs to the equation <code>cv2.countNonZero((n1)/cv2.countNonZero(n2))</code>.</p>

<p>Here F1 is a binary image (F as in foreground) and B1 is also binary image (B as in Background). I am trying to compute the ratio of non zero pixels in foreground vs background. </p>

<p>r should be calculated for F1/B1 and in the next iteration F2/B2 ... so on</p>

<pre><code>f_1_nz = f_1[f_1 != 0].size
# etc.

r_1 = f_1_nz / b_1_nz
# etc.
</code></pre>

<p>Ideally you'd put f_1 etc. into a list and iterate over it, instead of defining new names for each, see the answer by @apnorton.</p>

<p>So, in the end:</p>

<pre><code>for ff, bb in zip(f,b):
    f_nz = ff[ff != 0].size
    b_nz = bb[bb != 0].size
    print f_nz/b_nz
</code></pre>

python string for-loop