Komz Komz - 2 months ago 10
Python Question

print average percentage of a student from an array

The program is supposed to calculate and print out a given student's average percentage.

Unfortunately I am only able to print out the average percentage of the last student name in the array.
I want to know where exacltly I am going wrong with my coding.
Thanks. Heres my code below.

def averagepercentage():

scores = int(name_marks[1]),int(name_marks[2]),int(name_marks[3])
ap = sum(scores)/3

return ap

N = int(input('Number of students: ')) # total number of students
marks = int()
arr = []

for i in range(N):
name_marks = input('name & marks').split() #enter name & three different scores
name = str(name_marks[0])
arr.append(name)
print(arr)

student_name = str(input('student_name'))
for x in arr:
if student_name in x:

print (x)

print("%.2f" %averagepercentage())

Answer

In your first loop:

for i in range(N):
    name_marks = input('name & marks').split() #enter name & three different scores 
    name = str(name_marks[0])
    arr.append(name)
    print(arr)

you don't store the marks of the previous students, you replace your variable name_marks by the last marks from your input

the if student_name in x: looks if student_name is included in x, which is not exactly what you want to do, consider doing if student_name == x: instead.

Then:

def averagepercentage():

    scores = int(name_marks[1]),int(name_marks[2]),int(name_marks[3])
    ap = sum(scores)/3

    return ap

looks at the global variable name_marks to compute the average, but this variables only contains the value of the last student (because of my first remark)

what you can do, to keep most of your code structure is:

for i in range(N):
    name_marks = input('name & marks').split() #enter name & three different scores 
    name = str(name_marks[0])
    arr.append((name,averagepercentage()))
    print(arr)

student_name = str(input('student_name'))

for x in arr:
    if student_name in x:
        print ("student :" + x[0])
        print("average :" + x[1])
Comments