Randomly Select an Option with Questionary Library

  • Share this:

Code introduction


The function uses the Questionary library to randomly select an option from a given list of choices and returns the text of the selected option.


Technology Stack : Questionary

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_choice(questionary, choices):
    """
    Generate a random choice from a list of choices based on Questionary library.

    Args:
        questionary (Questionary object): The Questionary object to use for the prompt.
        choices (list): A list of strings representing the choices to present to the user.

    Returns:
        str: The randomly chosen option from the list.
    """
    from questionary import Choice

    # Create a Choice object for each option in the list
    choice_objects = [Choice(text=choice) for choice in choices]

    # Present the choices to the user and get the selected choice
    selected_choice = questionary.select("Choose an option:", *choice_objects).ask()

    # Return the text of the selected choice
    return selected_choice.text                
              
Tags: