Python: Calculate Average Score

Iterate through list of student names/scores to calculate average score

nick3499
2 min readSep 15, 2017

if __name__ == '__main__':
Evaluates to True only when this script is executed as a stand-alone program. In other words, if this script was imported, it’s name would no longer be __main__, and the instructions below that if statement would not execute. This can also be used exclusively for global variables, to prevent conflicts caused by duplicated global variable names.

n = int(input())
For entering the numerical value which sets the range. 3 indicates that the data of three students will be entered line by line.

d = {}
Initializes an empty dictionary, which ultimately becomes {'Krishna': 68.0, 'Arjun': 77.0, 'Malika': 56.0}, after student data is entered manually. The dictionary increases with each iteration:

{'Krishna': 68.0}
{'Krishna': 68.0, 'Arjun': 77.0}
{'Krishna': 68.0, 'Arjun': 77.0, 'Malika': 56.0}

for _ in range(n):
The for loop iterates through its following instructions three times, since the value assigned to n is 3.

info = input().split()
For manually entering lines of space-separated student data, e.g. Krishna 67 68 69. .split() maintains a single space between each item in a line, since split() defaults to a single space. info will store the following lists:

['Krishna', '67', '68', '69']
['Arjun', '70', '98', '63']
['Malika', '52', '56', '60']

score = list(map(float, info[1:]))
For gathering only scores into a list. map(float, info[1:]) skips the first item in a line (student name), and converts each numerical value into a float, e.g. [67.0, 68.0, 69.0]. score will store the following lists:

[67.0, 68.0, 69.0]
[70.0, 98.0, 63.0]
[52.0, 56.0, 60.0]

d[info[0]] = sum(score) / float(len(score))
For calculating average score. len(score) will divide combined score total by number of scores, adding it to the dictionary. d[info[0]] stores the following average scores:

68.0
77.0
56.0

print('{:.2f}'.format(d[input()]))
Prints average score of named student, as a two-decimal numerical value, so the manually entered name Malika will be followed by her calculated average score which prints as 56.00, see below.

After executing the script, enter the data as shown below manually:

$ python calculate_average.py
3
Krishna 67 68 69
Arjun 70 98 63
Malika 52 56 60
Malika

The average score for Malika will print:

56.00

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet