Home > Enterprise >  How to quiz a User from Dictionary inputs in python?
How to quiz a User from Dictionary inputs in python?

Time:11-08

How can I ask the user the capitals of each state and tell them if they are correct or incorrect? If they are wrong can python reply with the correct answer and tally up their score at the end. I will post what I have below and what I wish for it to show once I run it.

statesAndCapitals={ "Alabama": "Montgomery",

                    "Georgia": "Atlanta",

                    "Arizona": "Phoenix",

                    "Arkansas": "Little Rock",

                    "California": "Sacramento",

                    "Ohio": "Columbus",

                    "Connecticut": "Hartford" }

I was expecting:

>>> 
What is the capital of Arizona? Phoenix
    Correct!
What is the capital of Connecticut? Hartford
    Correct!
What is the capital of Colorado? Denver
    Correct!
What is the capital of California? Sacramento
    Correct!
What is the capital of Alaska? I forget
    Incorrect.  The answer was  Juneau
What is the capital of Arkansas? Little Rock
    Correct!
What is the capital of Alabama? abc
    Incorrect.  The answer was  Montgomery
.......
***Your score is :  5  out of  10

CodePudding user response:

Its not a complete answer; its just a simple idea to start :)

for x in statesAndCapitals.keys():
    answer = input(f"What is the capital of {x}? ")
    if (answer == statesAndCapitals[x]):
        print("Correct")

CodePudding user response:

Try this with random.choice

import random
n = 10
score = 0
choices = list(statesAndCapitals.keys())
for i in range(n):
  state = random.choice(choices)
  ans = input(f"What is the capital of {state}? : ")
  if ans == statesAndCapitals[state]:
    print("correct")
    score  = 1
  else:
    print("incorrect")
print(f"your total score: {score} out of {n}")
  • Related