3. [8 marks] Triangles Add some Python code so that the program displays the per
ID: 3620266 • Letter: 3
Question
3. [8 marks] TrianglesAdd some Python code so that the program displays the perimeter and area of a triangle of those dimensions. For the given declarations, the output should be:
1
The perimeter of a 3x4x5cm triangle is 12cm.
The area of a 3x4x5cm triangle is 6cm2.
When the TA marks this, they might change the values of the initial declarations, and
your code shall display the correct result for those new dimensions. For example, the
output of your code might instead be:
The perimeter of a 5x12x13cm triangle is 30cm.
The area of a 5x12x13cm triangle is 30cm2.
You should use Heron’s formula for calculating the area of a triangle. One version, for
side lengths a, b and c:
A =1/4 (a + b + c)(a + b - c)(a - b + c)(-a + b + c)
To find the square root in Python, you can do one of two things:
• Use the ** operator which evaluates an exponent in an expression. For example
the Python 2**3 would evaluate to 8.
• Use the sqrt() function from the math module. It’s a function but not a built-
in function, so to add it to your list of built-ins, you need to add the Python
from math import * somewhere above your first call to the sqrt() function.
Thinking Ahead
Some combinations of side lengths do not describe a valid triangle. For example, how
would you propose to construct a 3 × 5 × 10 triangle? It turns out that a triangle
is valid if the sum of any two of the sides is greater than or equal to the third, i.e.,
a + b ¸ c, b + c ¸ a and c + a ¸ b.
Try running your solution to question 3 with the side lengths 3, 5, 10 and the program
will crash. Why?
To protect your square root function from generating an error, you can write an
if/else statement that displays something appropriate, like
A 3x5x10 triangle is impossible.
Explanation / Answer
Dear.. def AREA_PROG(): # Area calculation program print "Area of a triangle!" print "perimeter of a trianle" print # Print out the menu print "Please choose a shape:" print "======================" print "1 Triangle" print "======================" # Recieve input foo = input("> ") # Start calculating elif foo == 1: base = input("Please enter the base:") height = input("Please enter the height:") area = .5*height*base print "The area is:", area print " " AREA_PROG() # perimeter of a triangle # Recieve input foo = input("> ") # Start calculating elif foo = 1: def triangle(x,y,z): sumOfSides=x+y+z angleX=math.acos((pow(y,2)+pow(z,2)-pow(x,2))*3.14/(360*y*z)) print “ The perimeter is :”, perimeter print PERIMETER_PROG()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.