1

Since I'm new to programming, please give me your notes for my code to calculate the average for 2 subjects :

from __future__ import print_function

Math_array= list()
pysics_array = list ()
M = raw_input ("enter the numebr of math marks:")
py= raw_input ("enter the numebr of pysics marks:")
Sum=0
Sum1=0
for x in range (int (M)):
    n=raw_input("math marks : ")
    Math_array.append(float (n))
Sum = sum(Math_array)

for z in range (int (py)):
    m=raw_input("pysics marks:")
    pysics_array.append(float (m))

Sum1= sum (pysics_array)


math_avr = Sum/ len(Math_array)
py_avr   = Sum1 / len (pysics_array)

print ("math avr",math_avr)
print ("math avr",py_avr)

1 Answer 1

1

One thing I wish someone had told me earlier when I started coding is that you should avoid explicitly writing code when you can use inbuilt functions or modules. Here, you can (and should) use Numpy to calculate the mean, rather than explicitly summing and dividing.:

from __future__ import print_function
import numpy as np

Math_array= []
pysics_array = []
M = raw_input ("enter the number of math marks:")
py= raw_input ("enter the number of pysics marks:")

for x in range (int (M)):
    n=raw_input("math marks : ")
    Math_array.append(float (n))


for z in range (int (py)):
    m=raw_input("pysics marks:")
    pysics_array.append(float (m))



print ("math avr", np.mean(Math_array))
print ("physics avr", np.mean(pysics_array))
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much, it's really so useful function I just known.
I suggest you spend some time learning about Numpy and Pandas. They are both Python modules for efficient data analysis. You don't have to memorize all the functions. When writing code, you can always check stack overflow to see how other people have solved a similar problem more efficiently. Wish you the best!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.