Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Code "Clean-up"

djshadmegodjshadmego Posts: 27Member
Ok all you Python folk, I just wrote a program (with the help of a tutorial) and I need to find a better way of writing it.
Here is the code:[code]## This program runs a test of knowledge

true = 1
false = 0
list = ["What color is the daytime sky on a clear day?","blue","What is the answer to life, the universe and everything?","42","What is a three letter word for mouse trap?","cat","What sound does a truely advanced machine make?","ping"]
# First get the test questions
# Later this will be modified to use file io.
def get_questions():
# notice how the data is stored as a list of lists
return [["What color is the daytime sky on a clear day?","blue"],
["What is the answer to life, the universe and everything?","42"],
["What is a three letter word for mouse trap?","cat"],
["What sound does a truely advanced machine make?","ping"]]

# This will test a single question
# it takes a single question in
# it returns true if the user typed the correct answer, otherwise false
def check_question(question_and_answer):
#extract the question and the answer from the list
question = question_and_answer[0]
answer = question_and_answer[1]
# give the question to the user
given_answer = raw_input(question)
# compare the user's answer to the testers answer
if answer == given_answer:
print "Correct"
return true
else:
print "Incorrect, The correct answer was:",answer
return false

# This will run through all the questions
def run_test(questions):
if len(questions) == 0:
print "No questions were given."
# the return exits the function
return
index = 0
right = 0
while index < len(questions):
#Check the question
if check_question(questions[index]):
right = right + 1
#go to the next question
index = index + 1
#notice the order of the computation, first multiply, then divide
print "You got ",right*100/len(questions),"% right out of",len(questions)
# Set variable for quiting

# Now make the menu
menu_item = 0
while menu_item != 9:
print "-----------------"
print "1. Take the test"
print "2. View the list of questions"
print "3. View the answers"
print "9. Quit"
print "-----------------"
menu_item = input("Pick an item from the menu: ")
if menu_item == 1:
run_test(get_questions())
elif menu_item == 2:
print list[0]
print list[2]
print list[4]
print list[6]
elif menu_item == 3:
print list[1]
print list[3]
print list[5]
print list[7]
print "Goodbye and Happy Holidays!"[/code]

My problem is that I couldn't figure out how to use the[code]def get_questions():
# notice how the data is stored as a list of lists
return [["What color is the daytime sky on a clear day?","blue"],
["What is the answer to life, the universe and everything?","42"],
["What is a three letter word for mouse trap?","cat"],
["What sound does a truely advanced machine make?","ping"]][/code]
function to print the questions and answers from the menu respectively without writing a seperate list.
The way I wrote it works, but I need to write it cleaner(for my peace of mind).
Thank you for your help

[hr][size=5][blue]d[/blue][italic][b][red]J[/red][/b][/italic][/size]

Comments

  • infidelinfidel Posts: 2,900Member
    Here's my first attempt at cleaning up your code. I went ahead and made a class to try to encapsulate the Test functionality as much as possible. I also left the __init__ method ready to read questions from a file. Note that True and False are already defined in Python (make sure you capitalize them properly, though).

    I felt that having a test object hold it's own questions and answers made more sense than having global lists or trying to pass lists around so much. And using the append() method of lists will make reading from a file much easier. The lists will grow as long as there are questions to read from the file. A simple loop should do it. Notice how easy it is to print the questions and answers if you keep them in separate lists. My other idea was to use a Dictionary object where the questions are the keys and the answers the values. But that might prove difficult because Dictionaries are not ordered.

    I also did the __name__ == '__main__' trick here so that you could import the TestOfKnowledge class into another program if you ever wanted to without having code execute that is only relevant to this particular instance of the test. Let me know if you don't understand something I did.

    [code]
    class TestOfKnowledge:

    def __init__(self, filename = None):
    """Create a Test object and load questions"""
    self.questions = []
    self.answers = []
    if filename == None:
    self.questions.append("What color is the daytime sky on a clear day?")
    self.answers.append("blue")
    self.questions.append("What is the answer to life, the universe and everything?")
    self.answers.append("42")
    self.questions.append("What is a three letter word for mouse trap?")
    self.answers.append("cat")
    self.questions.append("What sound does a truely advanced machine make?")
    self.answers.append("ping")
    else:
    pass

    def ask_question(self, index):
    """compare the user's answer to the actual answer"""
    if self.answers[index] == raw_input(self.questions[index] + " "):
    print "Correct"
    return True
    else:
    print "Incorrect, The correct answer was:", self.answers[index]
    return False

    def run_test(self):
    """Ask the user all of the questions in the test"""
    correct = 0
    for i in range(len(self.questions)):
    if self.ask_question(i):
    correct += 1
    score = (correct * 100) / len(self.questions)
    print "You got ", score, "% right out of", len(self.questions)

    def print_questions(self):
    print "
    ".join(self.questions)

    def print_answers(self):
    print "
    ".join(self.answers)

    if __name__ == "__main__":
    def main_menu():
    print "-----------------"
    print "1. Take the test"
    print "2. View the list of questions"
    print "3. View the answers"
    print "9. Quit"
    print "-----------------"
    try:
    selection = input("Pick an item from the menu: ")
    except:
    print "Invalid selection!"
    selection = 9
    return selection

    t = TestOfKnowledge()
    selection = main_menu()
    while selection != 9:
    if selection == 1:
    t.run_test()
    elif selection == 2:
    t.print_questions()
    elif selection == 3:
    t.print_answers()
    selection = main_menu()
    else:
    print "Goodbye and Happy Holidays!"
    [/code]

    : Ok all you Python folk, I just wrote a program (with the help of a tutorial) and I need to find a better way of writing it.
    : Here is the code:[code]## This program runs a test of knowledge
    :
    : true = 1
    : false = 0
    : list = ["What color is the daytime sky on a clear day?","blue",
    "What is the answer to life, the universe and everything?","42",
    "What is a three letter word for mouse trap?","cat",
    "What sound does a truely advanced machine make?","ping"]
    : # First get the test questions
    : # Later this will be modified to use file io.
    : def get_questions():
    : # notice how the data is stored as a list of lists
    : return [["What color is the daytime sky on a clear day?","blue"],
    : ["What is the answer to life, the universe and everything?","42"],
    : ["What is a three letter word for mouse trap?","cat"],
    : ["What sound does a truely advanced machine make?","ping"]]
    :
    : # This will test a single question
    : # it takes a single question in
    : # it returns true if the user typed the correct answer, otherwise false
    : def check_question(question_and_answer):
    : #extract the question and the answer from the list
    : question = question_and_answer[0]
    : answer = question_and_answer[1]
    : # give the question to the user
    : given_answer = raw_input(question)
    : # compare the user's answer to the testers answer
    : if answer == given_answer:
    : print "Correct"
    : return true
    : else:
    : print "Incorrect, The correct answer was:",answer
    : return false
    :
    : # This will run through all the questions
    : def run_test(questions):
    : if len(questions) == 0:
    : print "No questions were given."
    : # the return exits the function
    : return
    : index = 0
    : right = 0
    : while index < len(questions):
    : #Check the question
    : if check_question(questions[index]):
    : right = right + 1
    : #go to the next question
    : index = index + 1
    : #notice the order of the computation, first multiply, then divide
    : print "You got ",right*100/len(questions),"% right out of",len(questions)
    : # Set variable for quiting
    :
    : # Now make the menu
    : menu_item = 0
    : while menu_item != 9:
    : print "-----------------"
    : print "1. Take the test"
    : print "2. View the list of questions"
    : print "3. View the answers"
    : print "9. Quit"
    : print "-----------------"
    : menu_item = input("Pick an item from the menu: ")
    : if menu_item == 1:
    : run_test(get_questions())
    : elif menu_item == 2:
    : print list[0]
    : print list[2]
    : print list[4]
    : print list[6]
    : elif menu_item == 3:
    : print list[1]
    : print list[3]
    : print list[5]
    : print list[7]
    : print "Goodbye and Happy Holidays!"[/code]
    :
    : My problem is that I couldn't figure out how to use the[code]def get_questions():
    : # notice how the data is stored as a list of lists
    : return [["What color is the daytime sky on a clear day?","blue"],
    : ["What is the answer to life, the universe and everything?","42"],
    : ["What is a three letter word for mouse trap?","cat"],
    : ["What sound does a truely advanced machine make?","ping"]][/code]
    : function to print the questions and answers from the menu respectively without writing a seperate list.
    : The way I wrote it works, but I need to write it cleaner(for my peace of mind).
    : Thank you for your help
    :
    : [hr][size=5][blue]d[/blue][italic][b][red]J[/red][/b][/italic][/size]
    :

    [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

  • djshadmegodjshadmego Posts: 27Member
    You really opened my eyes on this one. You introduced a whole lot of new commands and ways of doing things! Though I still don't fully understand the _name_ = _main_ thing, well, as a matter of fact, I don't u nderstand it at all. I just take it cause you said so and I suspect that later I will understand this line. I do though understand most everything else and will be looking to incorperate that into my learning and future programs. There is one thing though.
    The def _init_ function...Could you have said "def init" or does it have to be "_init_" and if so...why? Ok, there are two things really. The second one is about encapsulating the test in a "class". What is that all about? Anyway, I hate to seem simple, but I really want to understand this so I can write my calendar and from there, other sites and programs... thanks a bunch as always!

    : Here's my first attempt at cleaning up your code. I went ahead and made a class to try to encapsulate the Test functionality as much as possible. I also left the __init__ method ready to read questions from a file. Note that True and False are already defined in Python (make sure you capitalize them properly, though).
    :
    : I felt that having a test object hold it's own questions and answers made more sense than having global lists or trying to pass lists around so much. And using the append() method of lists will make reading from a file much easier. The lists will grow as long as there are questions to read from the file. A simple loop should do it. Notice how easy it is to print the questions and answers if you keep them in separate lists. My other idea was to use a Dictionary object where the questions are the keys and the answers the values. But that might prove difficult because Dictionaries are not ordered.
    :
    : I also did the __name__ == '__main__' trick here so that you could import the TestOfKnowledge class into another program if you ever wanted to without having code execute that is only relevant to this particular instance of the test. Let me know if you don't understand something I did.
    :
    : [code]
    : class TestOfKnowledge:
    :
    : def __init__(self, filename = None):
    : """Create a Test object and load questions"""
    : self.questions = []
    : self.answers = []
    : if filename == None:
    : self.questions.append("What color is the daytime sky on a clear day?")
    : self.answers.append("blue")
    : self.questions.append("What is the answer to life, the universe and everything?")
    : self.answers.append("42")
    : self.questions.append("What is a three letter word for mouse trap?")
    : self.answers.append("cat")
    : self.questions.append("What sound does a truely advanced machine make?")
    : self.answers.append("ping")
    : else:
    : pass
    :
    : def ask_question(self, index):
    : """compare the user's answer to the actual answer"""
    : if self.answers[index] == raw_input(self.questions[index] + " "):
    : print "Correct"
    : return True
    : else:
    : print "Incorrect, The correct answer was:", self.answers[index]
    : return False
    :
    : def run_test(self):
    : """Ask the user all of the questions in the test"""
    : correct = 0
    : for i in range(len(self.questions)):
    : if self.ask_question(i):
    : correct += 1
    : score = (correct * 100) / len(self.questions)
    : print "You got ", score, "% right out of", len(self.questions)
    :
    : def print_questions(self):
    : print "
    ".join(self.questions)
    :
    : def print_answers(self):
    : print "
    ".join(self.answers)
    :
    : if __name__ == "__main__":
    : def main_menu():
    : print "-----------------"
    : print "1. Take the test"
    : print "2. View the list of questions"
    : print "3. View the answers"
    : print "9. Quit"
    : print "-----------------"
    : try:
    : selection = input("Pick an item from the menu: ")
    : except:
    : print "Invalid selection!"
    : selection = 9
    : return selection
    :
    : t = TestOfKnowledge()
    : selection = main_menu()
    : while selection != 9:
    : if selection == 1:
    : t.run_test()
    : elif selection == 2:
    : t.print_questions()
    : elif selection == 3:
    : t.print_answers()
    : selection = main_menu()
    : else:
    : print "Goodbye and Happy Holidays!"
    : [/code]
    :
    :
    : [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]
    :
    :

    [hr][size=5][blue]d[/blue][italic][b][red]J[/red][/b][/italic][/size]

  • infidelinfidel Posts: 2,900Member
    Well, I had a really long reply to this typed up but accidentally closed the browser window and lost it.

    : You really opened my eyes on this one. You introduced a whole lot of new commands and ways of doing things!

    I figured I might :-)

    : Though I still don't fully understand the _name_ = _main_ thing, well, as a matter of fact, I don't u nderstand it at all. I just take it cause you said so and I suspect that later I will understand this line.

    It's really not that hard. What does an "if" statement do? It says "if X is true, then execute the following code". What does "if __name__ == '__main__'" mean? It says "if the value of the variable __name__ is equal to the string '__main__' then execute the following code". __name__ is a special built-in variable that stores the name of a module. Every module has a name. The only difference is that Python gives the [italic]executing[/italic] module the special name of "__main__". If you know C or C++ or even Java, it's like Python is saying "this module is my main() function". If a module is imported by another module, then it will have a __name__ value equal to it's filename minus the .py extension. In our case here, if we type "python knowledge.py" at the command line, this script will be the one executing so it will have "__main__" as it's name. If we wrote another script that had a line "import knowledge" then that script would be "__main__" and this script would have a __name__ equal to "knowledge". What I'm trying to do here is say "only execute this block of code if this is the main() function.

    : The def _init_ function...Could you have said "def init" or does it have to be "_init_" and if so...why?

    It must be __init__ (with two underscores before and two after). Why? Because. It's the convention that the Python inventor decided to use to signify "special" names.

    : Ok, there are two things really. The second one is about encapsulating the test in a "class". What is that all about? Anyway, I hate to seem simple, but I really want to understand this so I can write my calendar and from there, other sites and programs... thanks a bunch as always!

    How much do you know about Object Oriented Programming?

    : : [code]
    : : class TestOfKnowledge:
    : :
    : : def __init__(self, filename = None):
    : : """Create a Test object and load questions"""
    : : self.questions = []
    : : self.answers = []
    : : if filename == None:
    : : self.questions.append("What color is the daytime sky on a clear day?")
    : : self.answers.append("blue")
    : : self.questions.append("What is the answer to life, the universe and everything?")
    : : self.answers.append("42")
    : : self.questions.append("What is a three letter word for mouse trap?")
    : : self.answers.append("cat")
    : : self.questions.append("What sound does a truely advanced machine make?")
    : : self.answers.append("ping")
    : : else:
    : : pass
    : :
    : : def ask_question(self, index):
    : : """compare the user's answer to the actual answer"""
    : : if self.answers[index] == raw_input(self.questions[index] + " "):
    : : print "Correct"
    : : return True
    : : else:
    : : print "Incorrect, The correct answer was:", self.answers[index]
    : : return False
    : :
    : : def run_test(self):
    : : """Ask the user all of the questions in the test"""
    : : correct = 0
    : : for i in range(len(self.questions)):
    : : if self.ask_question(i):
    : : correct += 1
    : : score = (correct * 100) / len(self.questions)
    : : print "You got ", score, "% right out of", len(self.questions)
    : :
    : : def print_questions(self):
    : : print "
    ".join(self.questions)
    : :
    : : def print_answers(self):
    : : print "
    ".join(self.answers)
    : :
    : : if __name__ == "__main__":
    : : def main_menu():
    : : print "-----------------"
    : : print "1. Take the test"
    : : print "2. View the list of questions"
    : : print "3. View the answers"
    : : print "9. Quit"
    : : print "-----------------"
    : : try:
    : : selection = input("Pick an item from the menu: ")
    : : except:
    : : print "Invalid selection!"
    : : selection = 9
    : : return selection
    : :
    : : t = TestOfKnowledge()
    : : selection = main_menu()
    : : while selection != 9:
    : : if selection == 1:
    : : t.run_test()
    : : elif selection == 2:
    : : t.print_questions()
    : : elif selection == 3:
    : : t.print_answers()
    : : selection = main_menu()
    : : else:
    : : print "Goodbye and Happy Holidays!"
    : : [/code]
    : :
    : :
    : : [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]
    : :
    : :
    :
    : [hr][size=5][blue]d[/blue][italic][b][red]J[/red][/b][/italic][/size]
    :
    :

    [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

Sign In or Register to comment.