Home » A simple python quiz example using a dictionary

A simple python quiz example using a dictionary

1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Programmer II [1Z0-816] Practice Tests
Oracle Java Certification
Spring Framework Basics Video Course
Java SE 11 Developer (Upgrade) [1Z0-817]

In this code example we show you how to use a dictionary to create a simple quiz, then you can loop through the questions and try and answer them

This is a fairly simple example which can be expanded upon and add extra functionality for learning, you can change the questions and answers, you can add a high score function, randomize the questions

Code

 

def make_questions():
    dictionary = {}
    dictionary['France'] = 'Paris'
    dictionary['Spain'] = 'Madrid'
    dictionary['UK'] = 'London'
    dictionary['Ireland'] = 'Dublin'
    dictionary['Italy'] = 'Rome'
    dictionary['Greece'] = 'Athens'
    dictionary['Russia'] = 'Moscow'
    dictionary['Algeria'] = 'Algeirs'
    dictionary['Turkey'] = 'Ankara'
    dictionary['Lebanon'] = 'Beirut'
    dictionary['Australia'] = 'Canberra'
    dictionary['Cuba'] = 'Havana'
    dictionary['Peru'] = 'Lima'
    dictionary['Portugal'] = 'Lisbon'
    dictionary['Norway'] = 'Oslo'
    dictionary['Canada'] = 'Ottawa'
    dictionary['Latvia'] = 'Riga'
    dictionary['Czech Republic'] = 'Prague'
    dictionary['Sweden'] = 'Stockholm'
    dictionary['Japan'] = 'Tokyo'
    return dictionary
	
def pick_question(dictionary): 
    count = 0
    for i in range(20):
        key, value = dictionary.popitem()
        print('Enter a capital for the country :', key)
        capital = input('Enter the capital: ')
        if capital == value:
            count += 1
            print('Right!')
    print('The number of correct answers is', count)
    print('The nubmer of incorrect answers is', 20 - count)
	
def main():
    dictionary = make_questions()
    pick_question(dictionary)
main()

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More