用Python计算三角形的面积和周长



嘿,伙计们,我在使用Heron公式输出给定边的三角形的面积和周长时遇到了问题。这是我的代码:

def main():
a = int(input('Enter first side: '))
b = int(input('Enter second side: '))
c = int(input('Enter third side: '))
def area():
    # calculate the sides
    s = (a + b + c) / 2
    # calculate the area
    area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
    return area
area()
def perimeter():
    # Calculate the perimeter
    perim = a + b + c
    return perim
perimeter()

print( 'Area is: ',format(area,'.1f'))
print( 'Perimeter is: ',format(perim,',.1f'))

main()

我收到了很多错误,比如

  • TypeError:传递给对象的非空格式字符串格式
  • NameError:未定义名称"perim"

我应该这样做的方法是在主函数中询问边,然后调用第二个边,然后用小数点后一位输出答案。

有人能告诉我我做错了什么吗?

您需要分配返回值,并使三个边长为全局。老实说,您应该阅读更多关于变量范围的内容,变量范围是定义变量的级别。此外,变量名不应覆盖函数名。通过这种方式,您可以稍后在脚本中的任何位置重用这些小函数,只需调用它们并传递三个参数。

例如:

def area(a, b, c):
    # calculate the sides
    s = (a + b + c) / 2
    # calculate the area
    area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
    return area
def perimeter(a, b, c):
    # Calculate the perimeter
    perim = a + b + c
    return perim
def main():   
    a = int(input('Enter first side: '))
    b = int(input('Enter second side: '))
    c = int(input('Enter third side: '))
    print "Area is:", area(a, b, c)
    print "Perimeter is:", perimeter(a, b, c)
main()

这应该是一种更干净的方法,并且只从主线程调用一个函数。您将避免声明全局变量和原始代码中的大量混乱(没有冒犯)。

您需要分配返回值,并使三个边长为全局。老实说,您应该阅读更多关于变量范围的内容,变量范围是定义变量的级别。此外,变量名不应覆盖函数名。

a = int(input('Enter first side: '))
b = int(input('Enter second side: '))
c = int(input('Enter third side: '))
def area():
    # calculate the sides
    s = (a + b + c) / 2
    # calculate the area
    area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
    return area
areaValue = area()
def perimeter():
    # Calculate the perimeter
    perim = a + b + c
    return perim
perim = perimeter()

print( 'Area is: ', format(areaValue,'.1f'))
print( 'Perimeter is: ', format(perim,',.1f'))
  • TypeError:请确保用一对大括号标记格式化参数。

    'Area is {}, perimeter is {}.'.format(first_value, second_value)
    
  • NameError:您可能想了解有关变量作用域的信息。

    def perimeter(a, b, c):
        # Calculate the perimeter
        perim = a + b + c
        return perim
    # Call the function with the parameters
    # you want it to compute :
    print "Perimeter is {}."format(
        perimeter(3, 4, 5)
        )
    # output : "Perimeter is 12."
    

最新更新