Ma Y
Ma Y

Reputation: 706

Writing loop insid a function changes the outputs

I wrote the following code, its out put is correct which is 35.

def ant(z, O_m, O_D):             
    return 1/(O_m * (1 + z)**3 + O_D)**(0.5)

def cc(k, H0, O_m, O_D):
    HH = H0 * (1/ant(zcc[k], O_m, O_D))
    hd =((Hcc[k] - HH)/sigcc[k])**2
    return hd

num = 0
for j in range(len(zcc)):
            num = num + cc(j, H0, O_m, O_D)    
print(num)  #35

but when I put it inside the loop it just prints the first number of the loop which is 0.02

def ccD(H0, O_m, O_D):
    for j in range(len(zcc)):
        num = 0
        num = num + cc(j, H0, O_m, O_D)
        return num
print(ccD(70, 0.3, 0.7))   #0.02

I wrote the data here:

zcc, Hcc, sigcc=np.genfromtxt('cc.txt',unpack=True)

0.0708  69     19.68
0.09    69      12
0.12    68.6    26.2
0.17    83      8
0.179   75        4
0.199   75      5
0.2     72.9   29.6
0.240   79.69   2.65
0.27    77       14
0.28    88.8    36.6
 0.35   84.4    7
0.352   83       14
0.38    81.5    1.9
0.3802  83    13.5
0.4       95    17
0.4004   77    10.2
0.4247  87.1    11.2
 0.43   86.45   3.68
0.44    82.6    7.8
0.4497  92.8    12.9
0.47    89       67
0.4783  80.9    9
 0.48   97      62
0.51    90.4    1.9
0.57    92.4    4.5
0.593   104     13
 0.6    87.9    6.1
0.61    97.3    2.1
0.68    92      8
0.73    97.3    7
0.781   105     12
0.875   125     17
0.88    90      40
0.9      117    23
1.037   154    20
1.3      168    17
1.363   160    33.6
1.43    177     18
1.53    140     14
1.75    202    40
1.965   186.5   50.4
2.34    222      7
2.336   226      8

thank you

Upvotes: 2

Views: 42

Answers (2)

Cyber
Cyber

Reputation: 867

You accidentally put num = 0 inside the for loop, meaning that num gets reset every time. Also it returns the first value because you indented the return statement to be inside the for loop.

This is what you want:

def ccD(H0, O_m, O_D):
    num = 0
    for j in range(len(zcc)):
        num = num + cc(j, H0, O_m, O_D)
    return num

Upvotes: 3

nicooo21
nicooo21

Reputation: 158

Your return statement is located inside the for loop so it will only iterate once. Put the return statement outside of the for loop. Also put num=0 outside of the for loop as the person above me noted.

def ccD(H0, O_m, O_D):
    num = 0
    for j in range(len(zcc)):
        num = num + cc(j, H0, O_m, O_D)
    return num

Upvotes: 1

Related Questions