Python函数调用报错‘solution未定义’,求正确调用方法及问题分析
问题分析与解决
报错原因
调用quiz_item(question,solution)时,全局范围内根本没定义question和solution这两个变量,自然会提示未定义错误。而且你的函数虽然声明了这两个参数,但函数内部直接把它们重新赋值成硬编码的内容,完全没用到传入的参数,等于参数白写了。
修正方案
分两种情况来调整:
方案1:让函数支持自定义题目和答案(复用性更强)
把题目文本和正确答案作为参数传入函数,函数内部不再硬编码:
def quiz_item(question_text, correct_solution): # 第一次提问 user_answer = input(question_text + " ") # 循环直到答对 while user_answer != correct_solution: user_answer = input("INCORRECT try again: " + question_text + " ") if user_answer == correct_solution: print("That is correct!") break # 调用时传入题目和正确答案 quiz_item("The blue whale is the biggest animal to have ever lived.", "T")
方案2:不需要参数,直接在函数内部写死题目和答案
如果不需要复用这个函数,直接去掉参数即可:
def quiz_item(): question_text = "The blue whale is the biggest animal to have ever lived." solution = "T" user_answer = input(question_text + " ") while user_answer != solution: user_answer = input("INCORRECT try again: " + question_text + " ") if user_answer == solution: print("That is correct!") break # 直接调用函数,不用传参数 quiz_item()
关键说明
- 函数内部赋值的变量默认是局部变量,外部访问不到,别把局部变量和全局变量搞混。
- 函数参数的意义是让函数更灵活,如果不需要外部传入值,就别声明参数;如果声明了参数,就要在函数内部用到它。
内容的提问来源于stack exchange,提问作者user19505926
相关产品推荐
相关产品推荐

