How to get the area of a hexagon in Python
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.
The formula for the area of a hexagon
To determine the regular hexagon’s area, we’ll apply the following formula:
Where:
- Area is the area of the hexagon.
- We’re using regular hexagons, so all sides have an equal length. That’s why we’re picking the one side of the length.
Example
Suppose we have each side length is 5. Then, calculate the area of the hexagon.
Code example
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))
Explanation
Let’s discuss the above code in detail.
Line 1: This line imports the
mathmodule, which provides the square root function (math.sqrt) that we’ll use to calculate the area of the hexagon.Line 3: The
hexagonfunction 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
areaofhexagonvariable.Line 5: The
returnstatement ends the function and returns the calculated area as the result of calling thehexagonfunction.Line 8: This line assigns a value of
5to the variableside_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
hexagonfunction with theside_lengthas an argument. This calculates the area of the hexagon using the formula and stores the result in theareaofhexagonvariable.
Quiz
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