Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why aren't the values from the for loop appending to the array?

I’m trying to append values from a for loop into a numpy array. While the values are correct, the array only returns none values. The values entered are from another numpy array.

import numpy as np
import matplotlib.pyplot as plt

j=np.array([14,15,16,16,16,22,22,24,24,25,25,25,25,25])
u=np.unique(j)


def P(age):
    sum=0
    for i in range(14):
        if j[i]==age:
            sum=sum+1
        else:
            sum=sum
    print(sum/14)
    
p = []
for i in range(6):
    p.append(P(u[i]))
p=np.array(p)
print(p)
print(type(p))

Output:

0.07142857142857142
0.07142857142857142
0.21428571428571427
0.14285714285714285
0.14285714285714285
0.35714285714285715
[None None None None None None]
<class 'numpy.ndarray'>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Function "P" doesn’t have a return function, hence equaling None each time.

def P(age):
    sum=0
    for i in range(14):
        if j[i]==age:
            sum=sum+1
        else:
            sum=sum
    print(sum/14)
    return sum/14

Shown here ^, you can return the sum.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading