进入' n'进入' n'

时间:2014-12-17 18:08:08

标签: python python-3.x

我正在研究一个问题,该问题使用字典存储州和大写字母,然后要求用户进行测验。当状态随机显示时,用户应该输入资本。如果用户是否正确,将通知用户。然后要求用户再次播放。当输入'n'时,它应该停止并给你正确和错误答案的数量。但是当输入'n'时循环继续播放,我无法获得要执行的最后一个语句。提前致谢。 为简洁起见,并未显示所有州和首都。

def main():
    states_caps = {'Alabama' : 'Montgomery' ,'Alaska': 'Juneau', 'Arizona': 'Pheonix',  'Arkansas':   'Little Rock', 'California': 'Sacramento','Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu'}

    print('Welcome to the Capitals of States quiz!')
    PlayAgain = "Y"
    correct_answer = 0
    incorrect_answer = 0
    while (PlayAgain =="Y"):
       for key in states_caps:
         print('\nThe state is:', key)
         capital = input('\nWhat is the capital?  ')
         if capital  == states_caps.get(key):
           print('You are correct!!')
           correct_answer +=1
         else:
           print('\nSorry, that is not correct.')
           print('The correct answer is,' , states_caps.get(key))
           incorrect_answer +=1
        PlayAgain = input("\nPlay again? (Y/N) ").upper()

    print('\nYou had', correct_answer, 'correct answers and',  incorrect_answer, 'incorrect answers.')

main()

1 个答案:

答案 0 :(得分:2)

要回答您的问题,这是因为您在询问用户是否想要再次播放之前遍历所有状态。下面有一个解决方案(如果用户将N回答为“再次播放”,则循环键并中断?

def main():
    states_caps = {'Alabama' : 'Montgomery' ,'Alaska': 'Juneau', 'Arizona': 'Pheonix',  'Arkansas':   'Little Rock', 'California': 'Sacramento','Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu'}

    print('Welcome to the Capitals of States quiz!')
    PlayAgain = "Y"
    correct_answer = 0
    incorrect_answer = 0
    states = list(states_caps.keys())
    for state in states:
        print('\nThe state is:', state)
        capital = input('\nWhat is the capital?  ')
        if capital  == states_caps.get(state):
            print('You are correct!!')
            correct_answer +=1
        else:
            print('\nSorry, that is not correct.')
            print('The correct answer is,' , states_caps.get(state))
            incorrect_answer +=1
        PlayAgain = input("\nPlay again? (Y/N) ").upper()
        if PlayAgain == 'N':
            break


    print('\nYou had', correct_answer, 'correct answers and',  incorrect_answer, 'incorrect answers.')

main()