Вы можете попробовать это. Эта версия программы будет постоянно предлагать пользователю вводить допустимые значения категории только в том случае, если пользователь вводит неправильную категорию. Наконец, он напечатает случайную запись из этой категории, когда пользователь вводит разрешенную категорию.
import random
# Store the category and values into a dictionary
categories = {
"objects": ["tables", "ladders", "chairs"],
"animals": ["chicken", "dog", "cat"],
"sports": ["basketball", "soccer", "rugby"]
}
def category():
print("Please enter category name: ")
response = ''
#Keep prompting the user to only enter allowed category values
while response.lower() not in categories:
# join(map(str, list((*categories,))) is used for retrieving the key values i.e. the category values from the dictionary "categories" and then join them as a string in order to display the allowed values back to the user
response = input(' One among the following [%s] : \n' % ', '.join(map(str, list((*categories,)))))
if response in categories:
word_list = categories.get(response)
# Print a random value from the chosen category
print(random.choice(word_list))
# Call the function
category()