This is neat, using json to drive your program. Unfortunately, you’re not entirely doing that.
You’ve hard coded the theme choices in the code. You really should be plucking them out of the json data. The program should have no knowledge of what’s in that data, only the structure.
Also, you should only load that source data once: never load it again.
So, we call something like this once, for the entire program:
def load_all_questions():
with open ('questionsen.json') as json_file_q_en:
python_dict_q_en = json.load(json_file_q_en)
return python_dict_q_en["trivia_game"]
Getting a list of available themes should be easy if you know the structure, which you do:
def avail_themes(all_questions):
return [x['theme'] for x in all_questions]
Or, if you’re unfamiliar with comprehensions:
def avail_themes(all_questions):
result = []
for x in all_questions:
result.append(x['theme'])
return result
I like that I can enter just a number for the theme. I don’t like that the rest of the time I have to type out the answer.
Here’s a function you could write:
def ask_question(question, choices):
# returns the choice num, you code here
Running it should look something like:
choices = ['Apples', 'Oranges']
choice = ask_question("What would you like?", choices)
print("you chose", choices[choice])
Result:
What would you like?
1) Apples
2) Oranges
Choice: 4
4 is not a valid choice, please try again.
What would you like?
1) Apples
2) Oranges
Choice: pear
pear is not a valid choice, please try again.
What would you like?
1) Apples
2) Oranges
Choice: 2
you chose Oranges
Once you have your ask_question
set up you should find other ways to simplify what you have.
Don’t want to throw any more at you, so good luck and have fun.