A hexagon is a polygon with six equal sides, each featuring six equal interior angles measuring 120 degrees. These sides can exhibit uniform lengths, forming regular hexagons or varying lengths, creating irregular hexagons. In this Answer, we’ll learn how to get the area of a regular hexagon in Python.
To determine the regular hexagon’s area, we’ll apply the following formula:
Where:
Suppose we have each side length is 5. Then, calculate the area of the hexagon.
Let’s find out how to implement the code using the above formula.
import mathdef hexagon(side_length):areaofhexagon = (3 * math.sqrt(3) * (side_length ** 2)) / 2return areaofhexagon# Given side lengthside_length = 5 # You can change this value to any desired side lengthareaofhexagon = hexagon(side_length)print("The area of the hexagon with side length {} is {:.3f}".format(side_length, areaofhexagon))
Let’s discuss the above code in detail.
Line 1: This line imports the math
module, which provides the square root function (math.sqrt
) that we’ll use to calculate the area of the hexagon.
Line 3: The hexagon
function takes one parameter, side_length
, This function will calculate the area of the hexagon.
Line 4: This line calculates the area using the provided side length and stores the result in the areaofhexagon
variable.
Line 5: The return
statement ends the function and returns the calculated area as the result of calling the hexagon
function.
Line 8: This line assigns a value of 5
to the variable side_length
, representing the length of a side of the hexagon. You can change this value to calculate the hexagon’s area for a different side length.
Line 10: It calls the hexagon
function with the side_length
as an argument. This calculates the area of the hexagon using the formula and stores the result in the areaofhexagon
variable.
Answer the quiz to test your understanding of the answer.
How many degrees are in each internal angle of a hexagon?
90 degrees
100 degrees
120 degrees
150 degrees
Free Resources