1

I am supposed to write a program that prompts the user for the lengths of three sides of a triangle, determines that the three lengths can form a triangle and if so uses Heron's formula to compute the area to 4 digits of precision.This is what I have so far I don't know where or how to put in the math

import math
def main():
    print()
    print("Triangle Area Program")
    print()
    a, b, c = eval(input("Enter three lengths separated by commas: "))
    print()
    s = (a+b+c) / 2.0
    area = sqrt(s*(s-a)*(s-b)*(s-c))
    if a > b:
        a, b = b, a
    if a > c:
        a, c = c, a
    if b > c:
        b, c = c, b
    else:
        a + b > c
        print("A triangle cannot be formed.")

main()
  • `math.sqrt` is what you need – roganjosh Sep 05 '16 at 18:59
  • 2
    Instead of using `eval` on that line, you could use `a,b,c = map(float, input('...').split(','))` – Moses Koledoye Sep 05 '16 at 19:01
  • this is what is supposed to happen "Triangle Area Program" Enter three lengths separated by commas: 3, 7, 9 Area of the triangle = 8.7856 square units mine says a triangle cannot be formed – Matt Poretsky Sep 05 '16 at 19:06
  • The else is only attached to `if b > c:`. Also you are never outputting your calculated area in any form – UnholySheep Sep 05 '16 at 19:06
  • so how do i attach the other parts and how do i output my calculated area – Matt Poretsky Sep 05 '16 at 19:09
  • In the else clause, the `a + b > c` instruction does nothing. I suppose you meant `if a+b > c` – daragua Sep 05 '16 at 19:09
  • Ok, so your question is really why you don't compute the area? Your function doesn't return anything, and `a + b > c` doesn't make much sense since I think that will just evaluate to a `bool`. Also, do you intend to evaluate every `if`? I think you mean to use `elif` because otherwise every operation interferes with the next. – roganjosh Sep 05 '16 at 19:09
  • @MattPoretsky sorry to sound condescending, but if you have to ask that question you need to find a good python tutorial and learn the basics. Chaining `if - elif - else` and using `return` are absolute basics of any programming language and should not have to be asked on SO – UnholySheep Sep 05 '16 at 19:15
  • yeah so i am still completely lost and confused i'm not sure what to change and when i do change what you are telling me nothing is working – Matt Poretsky Sep 05 '16 at 19:15
  • As @UnholySheep has stated, the reason that what we're saying won't make a lot of sense is that there are a number of issues with the code. It would take some time to fix all of them, and you'd be leapfrogging a lot of steps in understanding several core aspects. – roganjosh Sep 05 '16 at 19:18

2 Answers2

1

Here's a slightly modified version of your program that checks if the inputs are compatible in one compound conditional expression and replaces the use of eval:

import math

def main():
    print("\nTriangle Area Program\n")
    a, b, c = map(float, input("Enter three lengths separated by commas: ").split(','))

    if a + b > c and a + c > b and b + c > a:
        s = (a + b + c) / 2.0
        area = math.sqrt(s*(s-a)*(s-b)*(s-c))
        return round(area, 4) # round area to four decimal places
    else:
        raise ValueError("The inputs you entered cannot form a triangle")

if __name__ == '__main__':
    print(main())

More on avoiding eval when you can Why should exec() and eval() be avoided?

Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • this does not work after i enter the numbers a blank line comes after it – Matt Poretsky Sep 05 '16 at 19:22
  • This works but under the numbers it says "none" how do i get rid of that and how can i make the number limited to 4 digits – Matt Poretsky Sep 05 '16 at 19:45
  • @MattPoretsky As per `None`, I have a feeling you have `print(area)` instead of `return area` :) – Moses Koledoye Sep 05 '16 at 19:52
  • i see that however i need it to say "Area of the triangle = ,area, "square units." how do you suggest i do this. thanks – Matt Poretsky Sep 05 '16 at 20:00
  • You can do that with the `print` function. Replace `print(main())` with `print("Area of the triangle = ", main(), "square units.")` – Moses Koledoye Sep 05 '16 at 20:03
  • last question when i do this it only works correctly for 3,7,9 and 1,2,5. when i enter any other numbers all it does is print the numbers and not the "Area of the triangle = square units. – Matt Poretsky Sep 05 '16 at 20:22
  • import math def main(): print("Triangle Area Program") print() a, b, c = map(float, input("Enter three lengths separated by commas: ").split(',')) if a + b > c and a + c > b and b + c > a: s = (a + b + c) / 2.0 area = math.sqrt(s*(s-a)*(s-b)*(s-c)) print() return round(area, 4) else: print() print("A triangle cannot be formed.") if __name__ == '__main__': print("Area of the triangle =", main(), "square units.") – Matt Poretsky Sep 05 '16 at 20:22
1

Here's another possible version of your mathy problem:

import math


def heron(a, b, c):
    return 0.25 * math.sqrt((a + (b + c)) * (c - (a - b)) * (c + (a - b)) * (a + (b - c)))

if __name__ == "__main__":
    print()
    print("Triangle Area Program")
    print()
    print()

    try:
        description = "Enter three lengths separated by commas: "
        sides = sorted(map(float, input(description).split(',')))

        if (sides[1] + sides[2]) < sides[0]:
            print("A triangle cannot be formed.")
        else:
            a, b, c = sides
            print("Area of triangle {0}-{1}-{2} is {3:.4f}".format(
                sides[0], sides[1], sides[2], heron(a, b, c)))
    except Exception as e:
        print("Check your input!!!")
        print("--> Error: {0}".format(e))

Few notes about this version:

  • It's parsing your floating-point input values and sorting at the same time, that way you can check directly whether a triangle can be formed or not
  • It's not using the naive heron formula, instead is using another one which is numerically stable

I've decided to give you another version because in the comments you'll find some good advices about yours

BPL
  • 9,632
  • 9
  • 59
  • 117
  • this comes up with an error message after entering the numbers – Matt Poretsky Sep 05 '16 at 19:27
  • @MattPoretsky I've added some control error checks, you need to enter your input following this format `a,b,c`, that is , a string which contains three float numbers separated by commas – BPL Sep 05 '16 at 19:46
  • @MattPoretsky This version is already printing the area with 4 decimal digits, look at `{3:.4f}` – BPL Sep 05 '16 at 19:50