Skip to main content
 首页 » 编程设计

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

2024年10月25日11kevingrace

### 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 未定义。

注意:我的导师告诉我们,面积和周长只需要在 1 个函数中计算。他们不能分开。

有什么方法可以阻止该错误的发生?

请您参考如下方法:

你需要把

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'))