我相信我没有在我的程序中正确调用/返回函数
问题描述:
我不能让它正确运行,而且我必须使用3个函数,其目的是我将它们设置为的那些函数。我相信我没有在我的程序中正确调用/返回函数
def lw():
l = input("Enter the length of your rectangle: ")
w = input("Now enter the width of your rectangle:")
return l, w
def ap():
l,w = lw()
area = l * w
perimeter = 2*1 + 2*w
return area, perimeter
def main():
area,perimeter = ap()
print("With a length of", l ."and a width of", w)
print("the area of your rectangle is", area)
print("the perimeter of your rectangle is", perimeter)
if __name__ == "__main__":
main()
答
这应该工作
def lw():
l = input("Enter the length of your rectangle: ")
w = input("Now enter the width of your rectangle:")
return l, w
def ap():
l,w = lw()
area = l * w
perimeter = 2*1 + 2*w
return l, w, area, perimeter
def main():
l,w,area,perimeter = ap()
print("With a length of", l ,"and a width of", w)
print("the area of your rectangle is", area)
print("the perimeter of your rectangle is", perimeter)
if __name__ == "__main__":
main()
我已经做了两个变化:ap()
功能通过l
和w
和main()
功能访问它们。
答
Heyo,
我可以看到一些问题与您的代码:
- 第一
print
语句进行main
功能似乎是叫不说功能的范围内,存在的变量。除了area
和perimeter
之外,还需要返回ap()
中的l
和w
的值。此声明的参数中还有一个轻微的错字(.
,其中,
应该是)。 - 您的周长计算有点偏离。它乘以
2
乘以1
而不是2
乘以l
,渲染l
无用。 - 您的代码请求的输入仅返回
string
值而非数字值。您需要将其传入int()
或float()
,并返回这些函数的结果(如果您希望能够计算任何内容)。
'l'和'w'都是字符串,而不是整数或浮点数或任何您需要的数字。你需要在'int()'或'float'调用中包装'input(..)'调用。 –
另外,'l'和'w'是'lw'和'ap'函数中的局部变量。当代码被写入时,'main'不能访问它们。最后,我认为在周长计算中有一个错字。 – cco