Triangle in python

I have problems with my program that I have to do... here are the instructions: Write a program named triangle.py that uses a value-returning function that takes the lengths of the sides of a triangle as arguments and returns both the area and perimeter of the triangle. Prompt the user to enter the side lengths from the keyboard in the main function and then call the second function. Display the area and perimeter accurate to one decimal place. NOTE: Use Heron's Formula to find the area. I did it and it worked but the thing is he wants us to use one function that returns both area and perimeter.. so I re-did the program using one function but I keep getting an error saying per is not defined... I tried literally everything to fix it, looked online and nothing works. :( here is my code:

def main():

    a = float(input('Enter the length of the first side: '))
    b = float(input('Enter the length of the second side: '))
    c = float(input('Enter the length of the third side: '))



    print('The perimeter of the triangle is: ', format(per(a, b, c),',.1f'))

    print('The area of the triangle is: ', format(area(a, b, c),',.1f'))

def area_per(a, b, c):

    per = a + b + c
    s = per / 2
    area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
    return area_per


main()

The problem here is that the "per" variable you defined is local to the area_per function.

You'd need to create another function per that stands outside of that if you want the right scope.

def main():

    a = float(input('Enter the length of the first side: '))
    b = float(input('Enter the length of the second side: '))
    c = float(input('Enter the length of the third side: '))



    print('The perimeter of the triangle is: ', format(per(a, b, c),',.1f'))

    print('The area of the triangle is: ', format(area_per(a, b, c),',.1f'))

def area_per(a, b, c):

    p = per(a,b,c)
    s = p / 2
    area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
    return area

def per(a,b,c):
    return a+b+c  

main()
链接地址: http://www.djcxy.com/p/53138.html

上一篇: 使用函数的返回值

下一篇: python中的三角形