アメリカの州の首都を答えるテストを作るプログラム。
!/user/bin/env python # - Creates quizzes with questions and answers in # random order, along with the answer key. import random capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'NewMexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh', 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence', 'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont': 'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'WestVirginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} def main(): for quizNum in range(35): # Create the quiz and answer key files quizFile = open('capitalsquiz{}.txt'.format(quizNum + 1), 'w') answerkeyFile = open('capitalsquiz_answer{}.txt'.format(quizNum + 1), 'w') # Write out the header for the quiz quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n') quizFile.write((' ' * 20) + 'State Capitals Quiz (Form {})'.format(quizNum + 1)) quizFile.write('\n\n') # shuffle the order of the states states = list(capitals.keys()) random.shuffle(states) # loop through all 50 state, making a question for each for questionNum in range(50): # Get right and wriong answer correctAnswer = capitals[states[questionNum]] wrongAnswers = list(capitals.values()) del wrongAnswers[wrongAnswers.index(correctAnswer)] wrongAnswers = random.sample(wrongAnswers, 3) answerOptions = wrongAnswers + [correctAnswer] random.shuffle(answerOptions) # Wwite question and answer options to the quiz file quizFile.write('{}. What is the capital of {}\n'.format(questionNum + 1, states[questionNum])) for i in range(4): quizFile.write(' {}. {}'.format('ABCD'[i], answerOptions[i])) quizFile.write('\n') # Write the answer key to file answerkeyFile.write('{}. {}\n'.format(questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)])) quizFile.close() if __name__ == '__main__': main()
関数やクラスを使ったらもっとわかりやすく美しいソースコードになるかも。