Random Number and Choice Generator with Typer

  • Share this:

Code introduction


This code defines a Python script using the Typer library, which includes two features: generating a random number within a specified range, and selecting a random element from a list of choices.


Technology Stack : Typer, random

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import typer
import random

def random_number_generator(min_value, max_value):
    """
    Generate a random number between min_value and max_value.
    """
    return random.randint(min_value, max_value)

def random_choice choices, num_choices=1:
    """
    Return a random element from the non-empty sequence choices.
    """
    return random.choices(choices, k=num_choices)[0]

def main():
    app = typer.Typer()
    @app.command()
    def generate_random_number(min_value, max_value):
        """
        Generate a random number within a given range.
        """
        number = random_number_generator(min_value, max_value)
        typer.echo(f"Random number between {min_value} and {max_value}: {number}")

    @app.command()
    def pick_random_choice(choices):
        """
        Pick a random choice from a given list of choices.
        """
        choice = random_choice(choices)
        typer.echo(f"Random choice: {choice}")

    app.run()

# Code Information                
              
Tags: