python - 返回两个带有函数参数的值

标签 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 和 c 未定义。

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

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

最佳答案

你需要输入

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

在用户输入后的 main 中。因为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'))

关于python - 返回两个带有函数参数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28550786/

相关文章:

python - 仅与一项功能相关的昂贵的预先计算数据

python - 函数返回元组而不是字符串

pip - 我应该使用 pip 或 pip3 在虚拟环境中安装 python3 软件包吗?

python - 在不知道名称的情况下声明变量

python - 通过列表理解或任何其他方法解决嵌套字典迭代

python - 如果使用 python 和子进程从 pycharm 调用,gsutil 不起作用, "cannot import name _common"

python - pandas 使用 NaN 值排序时可能存在的错误

c++ - 如何遍历 TR1 元组

c# - 引用外部 dll 时由于某些元组错误而无法编译 c# 项目

python - 不能 "import matplotlib.pyplot as plt"