为什么要将变量分配给""?

时间:2015-11-10 05:16:13

标签: python variables python-3.x python-3.4

所以我正在Treehouse网站的Python课程中间,问题正是这样:

创建一个名为most_classes的函数,该函数包含教师字典。每个关键字都是教师的名字,他们的价值是他们所教授的课程清单。 most_classes应该返回班级最多的老师。

在这里,我已经在Treehouse论坛上的资源中找到了正确的代码,我已经问过同样的问题,但没有得到回复 - 那么究竟是什么分配老师=""做?我很困惑

 # The dictionary will be something like:
 # {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
 #  'Kenneth Love': ['Python Basics', 'Python Collections']}

 # Often, it's a good idea to hold onto a max_count variable.
 # Update it when you find a teacher with more classes than
 # the current count. Better hold onto the teacher name somewhere
 # too!

def most_classes(my_dict):
    count = 0
    teacher = "" #this is where I am confused!
    for key in my_dict: 
        if(len(my_dict[key]) > count):
            count = len(my_dict[key])
            teacher = key   

    return teacher

3 个答案:

答案 0 :(得分:0)

它为教师分配默认值,将替换为代码中的实际教师姓名。

答案 1 :(得分:0)

teacher = ""确保如果my_dict为空,则您无法在不设置teacher = key的情况下退出for循环。否则,如果my_dict为空,则会在未设置的情况下返回teacher

如果您注释掉该行,请按以下方式调用您的函数:

most_classes({})

你会得到这个(因为teacher永远不会在返回之前被初始化):

UnboundLocalError: local variable 'teacher' referenced before assignment

答案 2 :(得分:0)

为什么不删除该行并对其进行测试?

def most_classes(my_dict):
    count = 0
    teacher = "" # this is where I am confused!
    for key in my_dict:
        if(len(my_dict[key]) > count):
            count = len(my_dict[key])
            teacher = key

    return teacher


def most_classes_cavalier(my_dict):
    count = 0
    for key in my_dict:
        if(len(my_dict[key]) > count):
            count = len(my_dict[key])
            teacher = key

    return teacher


if __name__ == "__main__":
    dic = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
           'Kenneth Love': ['Python Basics', 'Python Collections']}
    print "The teacher with most classes is - " + most_classes(dic)
    print "The teacher with most classes is - " + most_classes_cavalier(dic)
    dic = {}
    print "The teacher with most classes is - " + most_classes(dic)
    print "The teacher with most classes is - " + most_classes_cavalier(dic)

这是我运行程序时得到的结果 -

The teacher with most classes is - Jason Seifer
The teacher with most classes is - Jason Seifer
The teacher with most classes is -
Traceback (most recent call last):
  File "experiment.py", line 30, in <module>
    print "The teacher with most classes is - " + most_classes_cavalier(dic)
  File "experiment.py", line 20, in most_classes_cavalier
    return teacher
UnboundLocalError: local variable 'teacher' referenced before assignment

我看到@ martijn-pieters已经提供了解释,但在这种情况下,Python解释器可以更快地为您完成。