Reputation: 35
I am trying to do a flash card quiz challenge in Python. This involves taking the states and their capitals from a text file. I've managed to strip and split in order to create a dictionary with keys.
But everytime I use random choice within the for loop it outputs the last key (e.g. Wyoming) On the other hand, when I take it out of the for loop, it only outputs the first key (e.g. Alabama)
Here is what it looks like (obviously this doesn't show the text file)
import random
with open("state_capitals.txt","r") as f:
for line in f:
cleanedLine = line.strip().split(',')
state = cleanedLine[0]
capital = cleanedLine[1]
d = {}
d[state] = capital
while len(d)>0:
choice = random.choice(list(d.keys()))
print("What is the capital city of",choice,"?")
answer=input("Answer: ")
Upvotes: 1
Views: 185
Reputation: 13175
The issue is that you have the while
loop inside the scope of the for
loop, so you never get a chance to populate your dictionary. However, moving the while
loop outside of the for
loop does not solve a different problem; you initialise d
within the for
loop, so that it keeps being reset back to an empty dictionary, removing all previous entries.
import random
d = {} # Create the dict once, otherwise each loop will delete all previous entries
with open("state_capitals.txt","r") as f:
for line in f:
cleanedLine = line.strip().split(',')
state = cleanedLine[0]
capital = cleanedLine[1]
d[state] = capital
# Move this outside the while loop. There's no need to recreate it on every iteration
states = list(d.keys())
# Move the while loop to be outside of the for loop
while len(d)>0:
choice = random.choice(states)
print("What is the capital city of",choice,"?")
answer=input("Answer: ")
# Allow the user to type Quit/quit to break the loop
if answer.lower() == 'quit':
break
Upvotes: 1
Reputation: 145
Your while len(d) > 0
is inside the for
loop, so during choice = random.choice(list(d.keys()))
the dictionary has only one key. You also reinitialize the dictionary in every for
loop iteration.
Upvotes: 0