[英]Why would you assign a variable to “”?
所以我在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
它為教師分配默認值,該默認值將替換為代碼中的實際教師姓名。
teacher = ""
確保如果my_dict
為空,則在未設置teacher = key
情況下不會退出for循環。 否則,如果my_dict
為空,則無需設置將返回teacher
。
如果注釋掉該行,請像下面這樣調用函數:
most_classes({})
您會得到的(因為teacher
在返回之前從未初始化過):
UnboundLocalError: local variable 'teacher' referenced before assignment
為什么不刪除該行並對其進行測試?
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解釋器會為您更快地完成該解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.