Python Forum

Full Version: Object oriented area of a triangle
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Please i need help, this code does not compute the area

# An object-oriented programming style to calculate area of triangle (1/2 base times height)

import sys
import math
a = input("Enter the value of the first side:")
b = input("Enter the value of the second side:")
c = input("Enter the value of the third side:")
class triangle():
   def __init__(self,a,b,c):
       self.a = a
       self.b = b
       self.c = c
   def area(a, b, c):
       s=(a + b + c)/2
       area=math.sqrt(s*(s-a)*(s-b)*(s-c))
       return area
print (area((a,b,c)))

------this is the output
Error:
Enter the value of the first side:4 Enter the value of the second side:5 Enter the value of the third side:6 Traceback (most recent call last): File "area2.py", line 17, in <module> print (area((a,b,c))) NameError: name 'area' is not defined
Your code is trying to use a global function area(), which doesn't exist.

area() is a method of a triangle object, it should take no arguments (except self), and should be used like so:
t = triangle(a, b, c)
print(t.area())
You'll also need to convert your inputs to numbers (using int() or float()), since input() returns strings on python 3.
Please can u explain further, at what lines should i make the corrections.

i have done this:
import sys
import math
a = 5
b = 6
c = 7
class triangle():
   def __init__(self,a,b,c):
       self.a = a
       self.b = b
       self.c = c
   def area(a, b, c):
       s=(a + b + c)/2
       area=math.sqrt(s*(s-a)*(s-b)*(s-c))
       return area
t = triangle(a, b, c)
print(t.area())
but it displays this error:
Error:
print(t.area()) eError: area() missing 2 required positional arguments: 'b' and 'c'
__________________-This code finally worked, thanks for helping me learn the hard way.
import sys
import math

a = int(input('Please enter the first side of a triangle: '))
b = int(input('Please enter the second side of a triangle: '))
c = int(input('Please enter the third side of a triangle: '))
class triangle():
   def __init__(self,a,b,c):
       self.a = a
       self.b = b
       self.c = c
   def area(self):
       s=(a + b + c)/2
       area=math.sqrt(s*(s-a)*(s-b)*(s-c))
       return area
t = triangle(a, b, c)
print(t.area())
_____Output
Output:
Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\TOPEV\Documents\School\Programming Language>python area2.py Please enter the first side of a triangle: 2 Please enter the second side of a triangle: 3 Please enter the third side of a triangle: 3 2.8284271247461903