Home > Enterprise >  How to declare variable outside the loop and set it to base value (float) in python?
How to declare variable outside the loop and set it to base value (float) in python?

Time:03-31

In this piece of code, I'm attempting to calculate the average of the person's scores as entered by the user. Code :

if __name__ == '__main__':
    n = int(input())
    student_marks = {}
    for _ in range(n):
        name, *line = input().split()
        scores = list(map(float, line))
        student_marks[name] = scores
    query_name = input()

for i in name:
    if(query_name == i):
        sos = float(sum(scores))
        lengs = int(len(scores))
        avg = float(sos/lengs)

print('.2f'%avg)

Error shown in the compiler :

Traceback (most recent call last): File "/tmp/submission/20220330/18/46/hackerrank-9395c8cfa7010e9d6e7964a4ac3c813/code/Solution.py", line 16, in module
print('.2f'%avg)
NameError: name 'avg' is not defined

CodePudding user response:

There's no need for a second loop at all. You have a dictionary indexed by name, so look up the scores you want to get by using query_name as a key:

student_marks = {}
for _ in range(int(input())):
    name, *line = input().split()
    scores = list(map(float, line))
    student_marks[name] = scores

query_name = input()
scores = student_marks[query_name]
print(f"{sum(scores)/len(scores):.2f}")

The loop for i in name was just iterating over the letters of name, which will just be whatever the last name you entered was; not at all useful for what you're trying to do.

Note that you also don't need any of the following:

  • if __name__ == '__main__' - this is only useful if you're working with multiple files, and the way you were using it, half of the code was outside the if block anyway.
  • int(len(...)) -- len already returns an int, no need to convert it
  • float(sum(...)) -- sum of a list of floats is already going to be a float
  • Related