当前位置:   article > 正文

Python异常处理:NameError: name ' ' is not defined,名称错误,名称“ ”未定义_name is not defined

name is not defined

代码段一:

"""
Author:  yeahthon
Date   :  2019-08-09  12:28:47
E-mail:  yeahthon@163.com
"""
class AnonymousSurvey():
    """收集匿名调查问卷的答案"""

    def  __init__(self, question):
        """储存一个问题,并为储存答案做准备"""
        self.question = question
        self.responses = []

    def  show_question(self):
        """显示调查问卷"""
        print(question)

    def  store_response(self,new_response):
        """储存单份调查问卷"""
        self.responses.append(new_response)

    def  show_results(self):
        """显示收集到的所有答案"""
        print("Survey result:")
        for  response in responses:
            print('- ' + response)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

代码段二:

"""
Author:  yeahthon
Date   :  2019-08-09  12:50:20
E-mail:  yeahthon@163.com
"""
from survey import  AnonymousSurvey

#定义一个问题,并创建一个表示调查的AnonymousSurvey对象
question = "what language did you first learn to speak?"
my_survey = AnonymousSurvey(question)

#显示问题并储存答案
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
    response = input("Language: ")
    if  response == 'q':
        break
    my_survey.store_response(response)

#显示调查结果
print("\nThink you to everyone cho participated in the survey!")
my_survey.show_results()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

运行时显示异常:

G:\python\untitled1\venv\Scripts\python.exe G:/python/untitled1/language_survey.py
Traceback (most recent call last):
  File "G:/python/untitled1/language_survey.py", line 13, in <module>
    my_survey.show_question()
  File "G:\python\untitled1\survey.py", line 16, in show_question
    print(question)
NameError: name 'question' is not defined

Process finished with exit code 1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

异常分析:名称question未被定义
异常处理:不能直接引用或者遍历形参, question在代码段一第9行已经定义为变量形参,引用输出时应当填入相应实参,即将代码段一第16行 question 改为 self.question,第25行 responses 改为 self.responses。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/645734
推荐阅读
相关标签
  

闽ICP备14008679号