在函数中返回带有参数的两个值
Returning two values with arguments in the function
### 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()
我正在尝试 return area 函数的两个值,但是当我尝试这样做时,我收到一条错误消息,指出当我尝试调用该函数时 a b 和 c 未定义。
注意:我的老师告诉我们,面积和周长只需要在一个函数中计算。他们不能分开。
有什么方法可以阻止该错误的发生?
你需要把
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)
。
### 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()
我正在尝试 return area 函数的两个值,但是当我尝试这样做时,我收到一条错误消息,指出当我尝试调用该函数时 a b 和 c 未定义。
注意:我的老师告诉我们,面积和周长只需要在一个函数中计算。他们不能分开。
有什么方法可以阻止该错误的发生?
你需要把
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)
。