SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Dictionaries And Sets
Exercise:
Programming Exercises
Question:2 | ISBN:9780132576376 | Edition: 2

Question

Capital Quiz
Write a program that creates a dictionary containing the U.S. states as keys and their capitals as values. (Use the Internet to get a list of the states and their capitals.) The program should then randomly quiz the user by displaying the name of a state and asking the user to enter that state’s capital. The program should keep a count of the number of correct and incorrect responses. (As an alternative to the U.S. states, the program can use the names of
countries and their capitals.)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Capital Quiz Program Code:

import random

#Initialize the dictionary of U.S. states and 
#their capitals
statesCapitals = {
    "Alabama": "Montgomery",
    "Alaska": "Juneau",
    "Arizona": "Phoenix",
    "Arkansas": "Little Rock",
    "California": "Sacramento",
    "India": "Delhi"
}

# Initialize variables for 
#correct and incorrect responses
correctAnswer = 0
incorrectAnswer = 0

# Quiz the user
for state in statesCapitals:
    capital = statesCapitals[state]
    inputData = input("What is the capital of {}? ".format(state))

    if inputData.lower() == capital.lower():
        print("Correct!")
        correctAnswer += 1
    else:
        print("Incorrect. The capital of {} is {}.".format(state, capital))
        incorrectAnswer += 1

# Display the final Quiz result scores as a count of 
#the number of correct and incorrect responses.
print("\nQuiz results:")
print("Correct responses: {}".format(correctAnswer))
print("Incorrect responses: {}".format(incorrectAnswer))

Executed Output:

What is the capital of Alabama? Juneau
Incorrect. The capital of Alabama is Montgomery.
What is the capital of Alaska? Juneau
Correct!
What is the capital of Arizona? Phoenix
Correct!
What is the capital of Arkansas? Sacramento
Incorrect. The capital of Arkansas is Little Rock.
What is the capital of California? Sacramento
Correct!
What is the capital of India? Delhi
Correct!

Quiz results:
Correct responses: 4
Incorrect responses: 2

 

0 0

Discussions

Post the discussion to improve the above solution.