Calculate Triangle Area with Typer CLI

  • Share this:

Code introduction


This code defines a function to calculate the area of a triangle and creates a command-line interface using the Typer library to allow users to input the base and height, then output the area.


Technology Stack : Typer

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
from typer import Typer, Argument, Option, confirm, echo

def calculate_area(base: float, height: float) -> float:
    """Calculate the area of a triangle.

    Args:
        base (float): The base length of the triangle.
        height (float): The height of the triangle.

    Returns:
        float: The area of the triangle.
    """
    return 0.5 * base * height

def main():
    app = Typer()
    
    @app.command()
    def triangle_area(base: float = Argument(..., help="The base length of the triangle."),
                       height: float = Argument(..., help="The height of the triangle.")):
        area = calculate_area(base, height)
        echo(f"The area of the triangle is: {area}")
    
    app.run()                
              
Tags: