Yao Jiang Yao Jiang - 28 days ago 5
Python Question

Trying to simplify my Python codes but shows syntax error: variable not defined

I was trying to simplify this:

def get_average(name):
homework=average(name["homework"])
quizzes=average(name["quizzes"])
tests=average(name["tests"])
weighted_mark= homework *0.1+ quizzes*0.3 + tests*0.6
return weighted_mark


So I use a loop:

def get_average(name):
component = ["homework","quizzes","tests"]
for thing in component:
thing = average(name[thing])
weighted_mark= homework *0.1+ quizzes*0.3 + tests*0.6
return weighted_mark


But the console shows syntax error: variable "homework" not defined.
Doesn't
thing = average(name[thing])

defined the variables?

This is the dictionary that I worked with

Answer

You can not create variables like that. thing = 2 will always leave you with a variable named thing, it doesn't matter what that name was pointing to before.

Since you don't have the coefficients structured, you still need to enumerate the three components during the print. If you want to get rid of this, you could create a dict:

weights = {
    "homework": 0.1,
    "quizzes": 0.3,
    "tests": 0.6,
}

and then use it like this

weighted_mark = sum(average(name[thing]) * weights[thing] for thing in [weights])