【问题标题】:I believe I am not properly calling / returning functions in my program我相信我没有在我的程序中正确调用/返回函数
【发布时间】:2017-09-07 20:12:01
【问题描述】:

我无法让它正确运行,我必须使用 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()

【问题讨论】:

  • lw 都是字符串,而不是整数或浮点数或您需要的任何数字。您需要将input(..) 调用封装在int()float 调用中。
  • 另外,lwlwap 函数中的局部变量。 main 无法访问它们,因为当前正在编写代码。最后,我认为周长计算有误。

标签: python-3.x return


【解决方案1】:

这应该可以工作

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() 函数中传递lw 并在main() 函数中访问它们。

【讨论】:

    【解决方案2】:

    喂,

    我可以看到您的代码存在许多问题:

    1. main 函数中的第一个 print 语句似乎正在调用该函数范围内不存在的变量。除了areaperimeter 之外,您还需要从ap() 返回lw 的值。此语句的参数中还有一个小错误(. 应该是 ,)。
    2. 你的周长计算有点不对劲。它将2 乘以1 而不是2 乘以l,使l 无用。
    3. 您的代码请求的输入仅返回string 值而不是数字值。如果您希望能够计算任何内容,您需要将它们传递到 int()float() 并返回这些函数的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-09
      • 2016-03-15
      • 2012-05-26
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      相关资源
      最近更新 更多