Python code to calculate area or circle, triangle, and rectangle

Here is the Python code to calculate the area of a circle, triangle, and rectangle:

import math

def area_circle(radius):
    return math.pi * radius**2

def area_triangle(base, height):
    return 0.5 * base * height

def area_rectangle(length, width):
    return length * width

print("Area of Circle with radius 2: ", area_circle(2))
print("Area of Triangle with base 4 and height 6: ", area_triangle(4, 6))
print("Area of Rectangle with length 3 and width 4: ", area_rectangle(3, 4))

The output of this code is:

Area of Circle with radius 2:  12.566370614359172
Area of Triangle with base 4 and height 6:  12.0
Area of Rectangle with length 3 and width 4:  12

Unit Test

Unit test for this code is as follows:

import unittest
import math

def area_circle(radius):
    return math.pi * radius**2

def area_triangle(base, height):
    return 0.5 * base * height

def area_rectangle(length, width):
    return length * width

class TestAreaFunctions(unittest.TestCase):
    def test_area_circle(self):
        self.assertAlmostEqual(area_circle(2), 12.566370614359172)
        
    def test_area_triangle(self):
        self.assertAlmostEqual(area_triangle(4, 6), 12)
        
    def test_area_rectangle(self):
        self.assertAlmostEqual(area_rectangle(3, 4), 12)

if __name__ == '__main__':
    unittest.main()

The tests use the assertAlmostEqual method to compare the expected and actual results, taking into account floating-point precision. The unittest.main() call at the end of the code runs the tests.

Explanation

This code contains a set of functions to calculate the area of different shapes (circle, triangle, and rectangle) and a unit test for these functions.

The area_circle function takes the radius of a circle as an input and returns its area using the formula pi * radius^2.

The area_triangle function takes the base and height of a triangle as inputs and returns its area using the formula 0.5 * base * height.

The area_rectangle function takes the length and width of a rectangle as inputs and returns its area using the formula length * width.

The TestAreaFunctions class defines a set of tests for the area_circle, area_triangle, and area_rectangle functions. Each test uses the assertAlmostEqual method from the unittest module to check if the result of the function is equal to an expected value, within a specified precision.

The if __name__ == '__main__': block at the end of the code is a standard Python idiom used to ensure that the tests are only run if the file is being executed as the main program (and not imported as a module). When executed as a standalone program, the unittest.main() call runs the tests defined in the TestAreaFunctions class.