'Homework' Question in Python Book: Write a program that prompts the user to enter 3 points of a triangle angle and display its area, using the equations given:
s = (side1 + side2 + side3) / 2
area = √s(s - side1)(s - side2)(s - side3)
The program I wrote when executed, displays an error, which I don't understand the root cause of and how to fix.
#Calculate the area of a triangle
# Enter coordinates for 3 points
sideOne = 1.5, -3.4#(x1, y1) = eval(input("Enter coords for side1:"))
sideTwo = 4.6, 5#(x2, y2) = #eval(input("Enter coords for side2:"))
sideThree = 9.5, -3.4#(x3, y3) = #eval(input("Enter coords for side3:"))
# Calculate s value
sideAll = (sideOne + sideTwo + sideThree) / 2# Compute Area
area = (sideAll(sideAll - sideOne)(sideAll - sideTwo)(sideAll - sideThree)) * * 0.5# Display Area
print("The Area of entered Triangle:", area)
Resulting Error
Traceback(most recent call last):
File "J:\Programming\PROGRAMMING\Python\Exercises\Chapter 2\Programming Exercises - 2.14 Skip.py", line 8, in < module >
sideAll = (sideOne + sideTwo + sideThree) / 2
TypeError: unsupported operand type(s) for / : 'tuple'
and 'int'
When you do sideOne = 1.5, -3.4
, then sideOne
is a tuple.
So it is basically (as you say in your comments) fthe coordinates of one of your 3 points in the form of (x,y)
, here (1.5, -3.4)
.
You cannot do arithmetic operations directly on tuples, it has no sense to do this because tuples are just a way of representing data and python does not guess that it is a coordinate.
Instead you can do mathematical operations on numerical values (integer, float and so on) but not on tuples.
Instead, you might want to compute the length of your side and then use it as given in your formula.
You might want to try something like this :
import math
#Calculate the area of a triangle
# Enter coordinates for 3 points
a = 1.5, -3.4#(x1, y1) = eval(input("Enter coords for side1:"))
b = 4.6, 5#(x2, y2) = #eval(input("Enter coords for side2:"))
c = 9.5, -3.4#(x3, y3) = #eval(input("Enter coords for side3:"))
# Calculate the length of the sides from the 3 triangle points
sideOne = math.sqrt( (b[0]-a[0])**2 + (b[1]-a[1])**2 )
sideTwo = math.sqrt( (c[0]-b[0])**2 + (c[1]-b[1])**2 )
sideThree = math.sqrt( (a[0]-c[0])**2 + (a[1]-c[1])**2 )
# Calculate s value
sideAll = (sideOne + sideTwo + sideThree) / 2 # Compute Area
area = math.sqrt(sideAll * (sideAll - sideOne) * (sideAll - sideTwo) * (sideAll - sideThree)) # Display Area
print("The Area of entered Triangle:", area)
Note I prefer to use the math.sqrt
function rather than non-integer power but this is just a matter of taste.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments