π Day 20/150 – Area of a Triangle in Python
Calculating the area of a triangle is a classic beginner-friendly problem that helps you understand formulas, user input, and different coding styles in Python.
The most common formula is:
Let’s explore multiple ways to implement this π
πΉ Method 1 – Basic Method (Direct Calculation)
base = 10
height = 5
area = 0.5 * base * height
print("Area of triangle:", area)
π§ Explanation:
- We directly assign values to base and height.
- 0.5 * base * height calculates the area.
- Simple and easy to understand.
π Best for: Quick calculations and beginners.
πΉ Method 2 – Taking User Input
base = float(input("Enter base: "))
height = float(input("Enter height: "))
area = 0.5 * base * height
print("Area of triangle:", area)
π§ Explanation:
- input() allows user interaction.
- float() converts input into numbers.
- Same formula is applied afterward.
π Best for: Dynamic, real-world scenarios.
πΉ Method 3 – Using a Function
def triangle_area(b, h):
return 0.5 * b * h
print(triangle_area(10, 5))
π§ Explanation:
- Function triangle_area() takes b and h as parameters.
- return gives back the computed value.
- Makes code reusable and clean.
π Best for: Structured and reusable programs.
πΉ Method 4 – Using Lambda Function
area = lambda b, h: 0.5 * b * h
print(area(10, 5))
π§ Explanation:
- lambda is a short, one-line function.
- Useful for simple operations without defining a full function.
π Best for: Short and quick logic.
.png)

0 Comments:
Post a Comment