我在弄清楚为什么在包含Docstring时我的代码失败的问题,特别是在函数select_level():
上
如果我删除文档字符串并注释掉,它会很好,但是
如果我包含Docstring,则在终端上会出现以下错误:
(NameError:未定义名称“ select_level”)
def select_level():
"""Defines how a player selects a difficulty, selects questions
and answers depending on user input,outputs selections.
"""
print ("Ready Player One! Select a level.")
level_name = raw_input("Type in easy, medium or hard\n").lower()
if level_name=="easy":
level(easy_level, blanks, easy_answers)
elif level_name=="medium":
level(medium_level, blanks, medium_answers)
elif level_name=="hard":
level(hard_level, blanks, hard_answers)
else:
print ("Please select easy, medium or hard")
print select_level()
答案 0 :(得分:0)
我有一些建议:
确保select_level()被正确调用并且确实已定义。
我问是因为它说
(The error says (NameError: name 'select_level' is not defined).
还,您是否尝试过在最后一行添加括号?
print(select_level())
答案 1 :(得分:0)
您的问题很可能是缩进。您的代码中有多个功能吗?如果是这样,请确保select_level函数未嵌套在另一个函数中。提供您的代码时,我无法重现您的错误。但是当我将您的函数嵌套在这样的另一个函数中时:
def my_other_function():
print "This is my other function"
def select_level():
"""Defines how a player selects a diffuclity, selects questions
and answers depending on user input,outputs selections.
"""
print ("Ready Player One! Select a level.")
level_name = raw_input("Type in easy, medium or hard\n").lower()
if level_name=="easy":
level(easy_level, blanks, easy_answers)
elif level_name=="medium":
level(medium_level, blanks, medium_answers)
elif level_name=="hard":
level(hard_level, blanks, hard_answers)
else:
print ("Please select easy, medium or hard")
然后尝试调用select_level函数,该函数会因您遇到的相同错误而中断。看到第二个函数比第一个函数缩进更多吗?这就是导致错误的原因。
由于该函数嵌套在另一个函数中,因此超出了范围。有关python范围的更多信息,give this page a read。
此外,您提供的代码示例还有另外两个问题。
删除代码最后一行的缩进。所以看起来像这样:
def select_level():
"""Defines how a player selects a diffuclity, selects questions
and answers depending on user input,outputs selections.
"""
print ("Ready Player One! Select a level.")
level_name = raw_input("Type in easy, medium or hard\n").lower()
if level_name=="easy":
level(easy_level, blanks, easy_answers)
elif level_name=="medium":
level(medium_level, blanks, medium_answers)
elif level_name=="hard":
level(hard_level, blanks, hard_answers)
else:
print ("Please select easy, medium or hard")
print select_level()
在函数上使用print语句时,它将尝试打印返回值。您的函数没有返回值,因此根本不需要print语句。删除它,使您的代码如下所示:
def select_level():
"""Defines how a player selects a diffuclity, selects questions
and answers depending on user input,outputs selections.
"""
print ("Ready Player One! Select a level.")
level_name = raw_input("Type in easy, medium or hard\n").lower()
if level_name=="easy":
level(easy_level, blanks, easy_answers)
elif level_name=="medium":
level(medium_level, blanks, medium_answers)
elif level_name=="hard":
level(hard_level, blanks, hard_answers)
else:
print ("Please select easy, medium or hard")
select_level()