Home > database >  Loop through dictionary with selecting random values working unproperly
Loop through dictionary with selecting random values working unproperly

Time:04-08

This script should use a while loop to iterate through the dictionary and grab a random state and capital, assigning each to a variable. The user is then asked what the capital of the randomly picked state is. The loop continues forever, asking the user what the capital is, unless the user either answers correctly or types "exit".

If the user answers correctly, "Correct" is displayed after the loop ends. However, if the user exits without guessing correctly, the answer is displayed along with "Goodbye."

Note: Make sure the user is not punished for case sensitivity. In other words, a guess of "Denver" is the same as "denver". The same rings true for exiting - "EXIT" and "Exit" are the same as "exit".

My code:

capitals_dict = {
    'Alabama': 'Montgomery',
    'Alaska': 'Juneau',
    'Arizona': 'Phoenix',
    'Arkansas': 'Little Rock',
    'California': 'Sacramento',
    'Colorado': 'Denver',
    'Connecticut': 'Hartford',
    'Delaware': 'Dover',`
}

import random

while True:
    b = random.choice(list(capitals_dict))
    c = capitals_dict.get(b)
    a = input(f'what the capital of the {b} is?: ').capitalize()
    if a == c:
        break
    print('Correct')
    if a == 'Exit'.lower():
        break
    print(c, "Goodbye")

This implementations doesn't work. For example, it asks "what the capital of the Pennsylvania is?" Answering 'exit' yields the output:

Correct
Harrisburg Goodbye

CodePudding user response:

This set of lines is incorrect:

    if a == c:               # Evaluates to False
        break                # Does not execute because the if statement evaluated to false.
    print('Correct')         # Prints 'Correct'
    if a == 'Exit'.lower():  # Evaluates to False, because you used `.capitalize()` on the input
        break                # Is not executed, the if statement evaluated to false
    print(c, "Goodbye")      # Prints the city and 'Goodbye'

When you say if a == c: you're checking if they are correct. In that case you should first print 'Correct' and then break. That looks like:

if a == c:
    print("Correct!")
    break

Then you need a second case handled by a different if statement to see if you should break out of the loop. You have the exact same problem, plus an additional problem where you used lower() instead of capitalize():

if a == 'Exit'.capitalize():
    print(c, "Goodbye")
    break

Remember, things will always happen in order - if you put a break in it will exit the loop and the next line will not be executed. In Python these 'scopes' (inside the function, inside the function and inside the loop, inside the function and inside the loop and the if statement) are all handled by indentations.

As an addendum - the point of using lower() and capitalize() is to change all the characters to their upper or lower case version. When using it to match a control statement (a == 'Exit'), you should make sure you're using the same one. Both the input string and the match string should use either lower() or capitalize().

Full code would look like:

capitals_dict = {
    'Alabama': 'Montgomery',
    'Alaska': 'Juneau',
    'Arizona': 'Phoenix',
    'Arkansas': 'Little Rock',
    'California': 'Sacramento',
    'Colorado': 'Denver',
    'Connecticut': 'Hartford',
    'Delaware': 'Dover',`
}

import random

while True:
    b = random.choice(list(capitals_dict))
    c = capitals_dict.get(b)
    a = input(f"What is the capital of {b}?").capitalize()
    if a == c:
        print('Correct')
        break
    if a == 'Exit'.capitalize():
        print(c, "Goodbye")
        break
    print(f"The answer was actually {c}. Try again.")

CodePudding user response:

Remember to place the print in the correct places - before the break. like so:

import random

capitals_dict = {
    'Alabama': 'Montgomery',
    'Alaska': 'Juneau',
    'Arizona': 'Phoenix',
    'Arkansas': 'Little Rock',
    'California': 'Sacramento',
    'Colorado': 'Denver',
    'Connecticut': 'Hartford',
    'Delaware': 'Dover',
}

while True:
    b, c = random.choice(list(capitals_dict.items()))
    a = input(f'what the capital of the {b} is?: ').capitalize()
    if a == c:
        print('Correct')
        break
    elif a.lower() == 'exit':
        print(c, "Goodbye")
        break
    else:
        print('Incorrect')
  • Related