我相信我没有在我的程序中正确调用/返回函数

问题描述:

我不能让它正确运行,而且我必须使用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() 
+1

'l'和'w'都是字符串,而不是整数或浮点数或任何您需要的数字。你需要在'int()'或'float'调用中包装'input(..)'调用。 –

+1

另外,'l'和'w'是'lw'和'ap'函数中的局部变量。当代码被写入时,'main'不能访问它们。最后,我认为在周长计算中有一个错字。 – cco

这应该工作

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()功能通过lwmain()功能访问它们。

Heyo,

我可以看到一些问题与您的代码:

  1. 第一print语句进行main功能似乎是叫不说功能的范围内,存在的变量。除了areaperimeter之外,还需要返回ap()中的lw的值。此声明的参数中还有一个轻微的错字(.,其中,应该是)。
  2. 您的周长计算有点偏离。它乘以2乘以1而不是2乘以l,渲染l无用。
  3. 您的代码请求的输入仅返回string值而非数字值。您需要将其传入int()float(),并返回这些函数的结果(如果您希望能够计算任何内容)。