After this tutorial, you will be able to write a Python program to find the hypotenuse of the right-angle triangle.
Finding the hypotenuse of a right-angle triangle in Python is a pretty simple task.
You can use the formula c = √(a² + b²) to find the hypotenuse of a right-angle triangle.
Simple Code
from math import sqrt
print('Enter the length of the shorter sides')
a = float(input('a : '))
b = float(input('b : '))
c = sqrt(a ** 2 + b ** 2)
print('Hypotenuse :' , c)
Output
Enter the length of the shorter sides
a : 12
b : 12
Hypotenuse : 16.97056274847714
Program with wrong input(exception) handling
from math import sqrt
def main():
while True:
try:
print('Enter the length of the shorter sides')
a = float(input('a : '))
b = float(input('b : '))
c = sqrt(a ** 2 + b ** 2)
print('Hypotenuse :' , c)
break
except:
print('Invalid Input')
main()
Output
Enter the length of the shorter sides
a : text
Invalid Input
Enter the length of the shorter sides
a : 12
b : 12
Hypotenuse : 16.97056274847714
Explained: Python Program To Find Hypotenuse of Right Angle Triangle
#from math library import sqrt(to find the square root)
from math import sqrt
#this program will run on loop until it is executed successfully!
while True:
#first python will try the code written in the try block
#if any occurs, the code of the except block will be executed and program will run again
try:
print('Enter the length of the shorter sides')
#taking input of two sides a and b from the user, and then the float() will convert the input to float value
a = float(input('a : '))
b = float(input('b : '))
#below is the formula to find the Hypotenuse of a right angle triangle
c = sqrt(a ** 2 + b ** 2)
print('Hypotenuse :' , c)
break
#if the try block fails to execute, i.e. user enters invalid input such as a text, this except block will be executed and the program will run again
except:
print('Invalid Input')
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.