Command-Line App for Random String Generation and Circle Area Calculation

  • Share this:

Code introduction


This function uses the Typer library to create a command-line application that accepts a string and an optional string length parameter. It then generates a random string and calculates the area of a circle with a random radius.


Technology Stack : Typer, random, string, math

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
from typer import Typer, Argument, Option
import random
import string
import math

def generate_random_string(length: int = 10):
    """Generate a random string of given length."""
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def calculate_circle_area(radius: float):
    """Calculate the area of a circle given its radius."""
    return math.pi * (radius ** 2)

def xxx(arg1: str = ..., arg2: int = ...):
    # Generate a random string and calculate the area of a circle with a random radius
    random_str = generate_random_string(len(arg1))
    random_radius = random.uniform(1, 100)
    area = calculate_circle_area(random_radius)
    
    # Output the random string and the calculated area
    print(f"Random String: {random_str}")
    print(f"Circle Area: {area}")

# Define the Typer application
app = Typer()

@app.command()
def run(
    arg1: str = Argument(..., help="Input a string"),
    arg2: int = Option(10, "--length", "-l", help="Length of the random string to generate")
):
    xxx(arg1, arg2)

# Run the Typer application
if __name__ == "__main__":
    app()