Reputation: 37
This is my dictionary:
def get_dic(filename):
count = 0
db = {}
filename = "words.txt"
with open(filename, "r") as infile:
for line in infile:
if line:
eng_words, spa_words = line.rstrip().split(":")
key = eng_words
val = spa_words.split(",")
db[key] = val
count += 1
print(count, "entries found.")
return db
this is the file it reads from and converts it to a dictionary:
library:la biblioteca
school:el colegio,la escuela
restaurant:el restaurante
movie theater:el cine
airport:el aeropuerto
museum:el museo
park:el parque
university:la universidad
office:la oficina,el despacho
house:la casa
Now I wanna call my db and make a "quiz" game using random() method after user inputs a number from 1 to 10. Since my list is only 10 lines.
import random
def main():
db = get_dic(filename)
random.shuffle(db)
for keyword in db(10):
display = "{}"
print(display.format(keyword))
userinput = input("Enter 1 equivalent Spanish word(s). Word [1]: ")
print(db[keyword])
print(" ")
if userinput == (db[key]):
print("correct!")
correct += 1
If input is "5", how do I get the program to print 5 words?
And I wanna return the score "correct" into another function that is not main(). Which will later write the score to a seperate .txt file, Is this possible? Do I just "return correct" and call it in a function like usual? I've only seen codes call function in "def main():"
output example if input choosen is 2:
English word: museum
Enter 1 equivalent Spanish word(s). Word [1]: el museo
Correct!
---
English word: school
Enter 2 equivalent Spanish word(s). Word [1]: el colegio
Word [2]: la escuela
Correct!
Upvotes: 0
Views: 77
Reputation: 2627
to validate the input you can also do
def get_num(text,err_text,verify):
try:
the_input = int(input(text))
if verift(the_input):
return the_input
else:
print(err_text)
return get_num(text,err_text)
except:
print(err_text)
return get_num(text,err_text)
#...
rounds = get_num('Enter a number of rounds (1-10): ', 'please enter an integer between 1 and 10', verify=lambda x:x>0 and x <11)
Upvotes: 0
Reputation: 39354
This may be what you want. I ask the user how many rounds first. (I have not validated this input, though)
def main():
db = get_dic(filename)
keys = list(db.keys())
random.shuffle(keys)
rounds = int(input('Enter a number of rounds (1-10): '))
correct = 0
for keyword in keys[:rounds]:
print(keyword)
userinput = input("Enter 1 equivalent Spanish word(s). Word [1]: ")
print(db[keyword])
print(" ")
if userinput == (db[keyword]):
print("correct!")
correct += 1
return correct
correct = main()
print(f'{correct} answers correct')
Upvotes: 3