# How to check if a given point lies inside a triangle or not in Python

In this tutorial, we will see **how to check a given point lies inside a triangle or not in Python. **This tutorial will be very interesting because here we learn a little bit about how to find the area of a triangle in coordinate geometry. The coordinate of three corner points of a triangle and one more point will be given by the user and we have to check whether this point will lie inside in the triangle or not.

**The steps that we will use to solve this problem are the following:-**

Let the coordinates of three corners of the triangle(MNO) are M(x1, y1), N(x2, y2) and O(x3, y3). And coordinates of another point(B) is (x, y).

- Calculate the area of the triangle MNO by using the coordinate geometry formula that we have learned. Let the area of the triangle(MNO) is A.

`A = (1/2)*[ x1(y2 – y3) + x2(y3 – y1) + x3(y1-y2)]`

- To check point B whether lies in the triangle or not, we have to find the area of the triangle BMN, BMO, and BNO by using the same formula that we have used to find A and assume these areas are A1, A2, and A3 respectively.
- If another point B lies inside the triangle MNO then A1+A2+A3 must be equal to A.

## Python program to check if a given point lies inside a triangle or not

So, let’s start writing the Python program. Before writing the code, we are assuming that the coordinates are provided by the user and these are the following:

`M(0,0), N(20,0), O(10,30), B(10,15)`

Python program:

def area(x1,y1,x2,y2,x3,y3): return abs((x1*(y2-y3)+(x2*(y3-y1))+(x3*(y1-y2)))/2.0) A=area(0,0,20,0,10,30) A1=area(0,0,20,0,10,15) A2=area(0,0,10,30,10,15) A3=area(20,0,10,30,10,15) If (A1)+(A2)+(A3)==A: print('The point B lies inside the triangle MNO.') else: Print('The point B does not lies inside the triangle MNO.')

Output:-

The point B lies inside the triangle MNO.

So Guy’s, I hope you find it useful.

Also read:

## Leave a Reply