Python | Check if Triangle is Right Angled or Not

Any triangle will be defined as Right Angled Triangle if it follows Pythagorus Theorem which states that sum of squares of other sides is equal to square of largest side. Like if a triangle have 3, 6, 7 as length of sides, then sum of squares of 32 + 62 = 9 + 36 = 45 which is not equal to 72 = 49. That’s why a triangle of length 3, 6, 7 is not a Right Angled Triangle.

This logic can be coded algorithmically as Python Code. Let’s see Python Code for Checking whether a Triangle is right angled or not.

# Checks if triangle is right angled or not using Python

a = float(input("Enter first side of triangle => "))
b = float(input("Enter second side of triangle => "))
c = float(input("Enter third side of triangle => "))

# Checks which side out of three a, b and c is largest
if (a >= b) and (a >= c):
	largest_triangle_side = a
elif (b >= c) and (b >= a):
	largest_triangle_side = b
else:
	largest_triangle_side = c

# Applying Pythagorean theorem to check if triangle is Right Angled

# If a is largest side of triangle
if (largest_triangle_side == a):
	if (b**2 + c**2 == a**2):
		print("Triangle is Right Angled")
	else:
		print("Triangle is Not Right Angled")

# If b is largest side of triangle
if(largest_triangle_side == b):
	if(c**2 + a**2 == b**2):
		print("Triangle is Right Angled")
	else:
		print("Triangle is Not Right Angled")

# If c is largest side of triangle
if(largest_triangle_side == c):
	if(a**2 + b**2 == c**2):
		print("Triangle is Right Angled")
	else:
		print("Triangle is Not Right Angled")  

Output of Above Code

Enter first side of triangle => 1
Enter second side of triangle => 2
Enter third side of triangle => 3
Triangle is Not Right Angled
People reacted to this story.
Show comments Hide comments
Comments to: Python | Check if Triangle is Right Angled or Not
  • November 6, 2021

    The problem with this code is that it will quickly lead to inaccuracies. For example, where a and b are both 10 and c is 10√2, it fails to recognise it as a right-angled triangle. Not much can be done, however, about Python’s built-in inaccuracies, without introducing a possible false negative:
    a ** 2 + b ** 2 == round(c ** 2) and (a ** 2 + b ** 2) ** 0.5 == c
    Now, with this, there are false negatives, but we likely don’t need the level of accuracy. For example, where a and b are both 10, and c is 2√10 – 10^-16, it has a false negative. Now, it is off by 0.0000000000000001, but who actually needs that exact level of accuracy for a triangle?

    Reply
    • November 9, 2021

      Yes Umar, your correct. This code is Ok if considered for generic lengths of sides.

      Reply

Write a response

Your email address will not be published.