print("Enter 'q' at any time to quit.") whileTrue: first = input("\nPlease give me a first name:") if first == 'q': break last = input("\nPlease give me a last name:") if last == 'q': break
defshow_results(self): """显示收集到的所有答案""" print("Survey results:") for response in self.responses: print('- ' + response)
其次基于该类编写程序,证明该类可正常运行,文件名为language_survey.py。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
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") whileTrue: response = input("Language: ") if response == 'q': break my_survey.store_response(response)
# 显示调查结果 print("\nThank you to everyone who participated in the survey!") my_survey.show_results()
然后编写测试代码,文件名为test_survey.py。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import unittest from survey import AnonymousSurvey
deftest_store_single_response(self): """测试单个答案会被妥善地存储""" question = "What language did you first learn to speak?" my_survey = AnonymousSurvey(question) my_survey.store_response('python')
defsetUp(self): """ 定义一个调查对象和一组答案,以供使用的测试方法使用 """ question = "What language did you first learn to speak?" self.my_survey = AnonymousSurvey(question) self.responses = ['python', 'C', 'C++']
deftest_store_single_response(self): """测试三个答案会被妥善存储""" for response in self.responses: self.my_survey.store_response(response) for response in self.responses: self.assertIn(response, self.my_survey.responses)