Python异常处理:NameError: 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)

代码段二:

"""
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()

运行时显示异常:

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

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

  • 17
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值