Python Forum
"Name is not defined" when running a class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
"Name is not defined" when running a class
#1
Hi. I'm a beginner trying to figure out why my code won't work. I'm pretty sure it's a minor detail, but I tried several time, but cannot find out why Huh

I'm trying to make a program that runs a survey by fetching methods from another module.

Appreciate your help. Thanks.

Module with class:
class AnonymousSurvey():
    """Collect anonymous answers to a survey question."""

    def __init__(self, question):
        """Store a question, and prepare to store responses."""
        self.question = question
        self.responses = []

    def show_question(self):
        """Show the survey question."""
        print(question)

    def store_response(self, new_response):
        """Store a single response to the survey."""
        self.responses.append(new_response)

    def show_results(self):
        """Show all the responses that have been given."""
        print("Survey results:")
        for response in responses:
            print('- ' + response)
My program:
from survey import AnonymousSurvey

# Define a question, and make a survey.
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)

# Show the question, and store responses to the 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)

# Show the survey results.
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()
Error traceback:
Error:
Traceback (most recent call last): File "C:/Users/Lenovo/Documents/Python/Examples_book/Page_223_language_survey.py", line 8, in <module> my_survey.show_question() File "C:\Users/Lenovo/Documents/Python/Examples_book\survey.py", line 13, in show_question print(question) NameError: name 'question' is not defined
Reply
#2
Need to add self. in front of question in the method show_question
Reply
#3
Do you mean like this? Maybe I misunderstood because I get the same traceback as last time.

def show_question(self):
        """Show the survey question."""
        print(self.question)
Error:
NameError: name 'question' is not defined
Reply
#4
Yes that is now correct also self. is missing from responses in the method show_results but that would not cause the error shown.
What is the full error traceback?

Did you make sure you saved survey after making the change
Reply
#5
Have now edited the method show_results as well
def show_results(self):
        """Show all the responses that have been given."""
        print("Survey results:")
        for response in self.responses:
            print('- ' + response)
Full error traceback is still the same:
Error:
Traceback (most recent call last): File "C:/Users/Lenovo/Documents/Python/Examples_book/Page_223_language_survey.py", line 8, in <module> my_survey.show_question() File "C:\Users/Lenovo/Documents/Python/Examples_book\survey.py", line 13, in show_question print(question) NameError: name 'question' is not defined

I'm sorry. I see that I messed up and mixed the file names when running the code. It's working now. Thank you! Blush
Reply
#6
If you have made the change, the error now does not match the code
print(self.question)
does not match
Error:
File "C:\Users/Lenovo/Documents/Python/Examples_book\survey.py", line 13, in show_question print(question)
As stated above did you make sure you saved survey after making the changes?
Reply
#7
Everything seems to be working now. The code looks like this after saving

Thanks again!

# survey.py - page 223

class AnonymousSurvey():
    """Collect anonymous answers to a survey question."""

    def __init__(self, question):
        """Store a question, and prepare to store responses."""
        self.question = question
        self.responses = []

    def show_question(self):
        """Show the survey question."""
        print(self.question)

    def store_response(self, new_response):
        """Store a single response to the survey."""
        self.responses.append(new_response)

    def show_results(self):
        """Show all the responses that have been given."""
        print("Survey results:")
        for response in self.responses:
            print('- ' + response)
Yoriz likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  super() and order of running method in class inheritance akbarza 7 737 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  Why built in functions are defined as class? quazirfan 5 2,805 Oct-23-2021, 01:20 PM
Last Post: Gribouillis
  Error when refering to class defined in 'main' in an imported module HeRo 2 2,387 Apr-13-2021, 07:22 PM
Last Post: HeRo
  Class function is not running at all even though it is clearly run in the code SheeppOSU 2 2,094 Sep-26-2020, 10:54 PM
Last Post: SheeppOSU
  Running scripts and location of saved interpreted user-defined classes and functions leodavinci1990 3 2,527 Aug-25-2020, 03:43 AM
Last Post: micseydel
  "Class already defined" while using typings. DreamingInsanity 0 2,333 Aug-19-2020, 10:43 AM
Last Post: DreamingInsanity
  python library not defined in user defined function johnEmScott 2 3,860 May-30-2020, 04:14 AM
Last Post: DT2000
  Python complains that class instance is not defined colt 3 5,649 Sep-17-2019, 12:32 AM
Last Post: ichabod801
  NameError: name 'display' is not defined when running code on power bi beginner1 2 19,182 Jul-24-2019, 11:03 AM
Last Post: beginner1
  saving (in text or binary) an object under a defined class cai0824 3 3,077 May-12-2019, 08:55 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020