#!/usr/bin/env python3 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. """A quick quiz program Provides a class that allows creation of other quizzes """ __all__ = ['main', 'multipleChoiceQuestion'] __author__ = "Cody A. Taylor ( codemister99@yahoo.com )" __version__ = "0.1.1 alpha" def main(): """Example quiz Note that you can use any mix of data-types, assuming it has a __str__ method """ quest = multipleChoiceQuestion answers = [] answers.append(quest("Where does the President live?", {"a": "Hollywood", "b": "Washington", "c": "Pittsburgh"}, "b").ask()) print(answers[-1]) answers.append(quest("What color is his house?", {"a": "White", "b": "Red", "c": "Green"}, "a").ask()) print(answers[-1]) answers.append(quest("The president is voted in by the public", {"t": True, "f": False}, "f").ask()) print(answers[-1]) correct_count = 0 total = len(answers) for index in range(total): if "Correct!" == answers[index]: correct_count += 1 print("You answered {} of {} correctly".format(correct_count, total)) def _lowerKeys(dictionary): """Return an exact copy of a dict with all keys in lower case""" _new_dict = {} for key in dictionary.keys(): _new_dict[key.lower()] = dictionary[key] return _new_dict class multipleChoiceQuestion(object): """Create a question, allowing quick creation of a quiz, or any multi-choice input scenario Note that `question` must be str, `answers` must be dict, and `correct` must be str """ def __init__(self, question=" ", answers={"a": None, "b": None, "c": None, "d": None}, correct="a"): assert correct.lower() in _lowerKeys(answers).keys(), "{} is an invalid answer".format(correct) self.question = question self.answers = _lowerKeys(answers) self.correct = correct.lower() def ask(self, returnCorrect="Correct!", returnIncorrect="Incorrect..."): """Ask your question while not valid guess: Print the question Print each answer with letter (not sorted yet) Input guess Test guess: Return boolean-like string """ guess = None while guess not in self.answers.keys(): print(self.question) for key in sorted(self.answers.keys()): print("\t{}: {}".format(key, self.answers[key])) guess = input("Answer: ").lower() if guess == self.correct: return returnCorrect else: return returnIncorrect __repr__ = ask __str__ = ask if __name__ == "__main__": main()