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

时间:2015-02-16 21:37:23

标签: python tuples python-3.4

### 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()

我试图从区域函数返回两个值,但是当我尝试这样做时,我得到一个错误,说当我尝试调用该函数时,未定义a和b。

注意:我的导师告诉我们,区域和周长只需要用1个函数计算。他们无法分开。

有没有办法可以阻止这种错误发生?

2 个答案:

答案 0 :(得分:2)

你需要把

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

在主用户输入后。因为a,b,c是在主函数

的范围内定义的

它应该是这样的:

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

答案 1 :(得分:0)

在将值分配给areaV, perimeterV = area(a, b, c)之前,您无法致电a, b, c