在函数中返回两个带参数的值

2024-06-16 09:09:40 发布

您现在位置:Python中文网/ 问答频道 /正文

### The formulas for the area and perimeter.
def area(a, b, c):
    # calculate the sides
    s = (a + b + c) / 2
    # calculate the area
    areaValue = (s*(s-a)*(s-b)*(s-c)) ** 0.5
    # returning the output

    # Calculate the perimeter
    perimValue = a + b + c
    # returning the output.

    return areaValue,perimValue

areaV, perimeterV = area(a, b, c)

### The main function for the prompts and output.
def main():
    # The prompts. 
    a = int(input('Enter first side: '))
    b = int(input('Enter second side: '))
    c = int(input('Enter third side: '))

    # The output statements. 
    print ("The area is:", format(areaV(a, b, c),',.1f'),"and the perimeter is:", format(perimeterV(a, b, c), ',.1f'))

### Calling msin
main()

我试图从area函数返回这两个值,但是当我尝试这样做时,我得到一个错误,当我尝试调用函数时,a b和c没有定义。你知道吗

注:我的指导老师告诉我们面积和周长只需要在一个函数中计算。他们不能分开。你知道吗

有没有办法阻止错误的发生?你知道吗


Tags: andtheforinputoutputmaindefarea
2条回答

你需要把

areaV, perimeterV = area(a, b, c) 

用户输入后在主界面中。因为a,b,c是在main函数的作用域中定义的

应该是这样的:

def main():
    # The prompts. 
    a = int(input('Enter first side: '))
    b = int(input('Enter second side: '))
    c = int(input('Enter third side: '))
    areaV, perimeterV = area(a, b, c)
    # The output statements. 
    print ("The area is:", format(areaV,',.1f'),"and the perimeter is:", format(perimeterV, ',.1f'))

在为a, b, c赋值之前,不能调用areaV, perimeterV = area(a, b, c)。你知道吗

相关问题 更多 >