You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何在函数内为变量赋值输入并实现跨函数访问?

解决Python矩形面积计算的作用域问题

你的问题出在两个地方:

  1. 函数作用域限制:area2函数无法直接访问main2里定义的x、y变量——Python中,函数内部的局部变量只能在自身函数范围内使用,其他函数不能直接调用。
  2. 未使用变量警告:你定义了z(height)但没用到它,所以会出现"variable not accessed"的提示。

下面是两种可行的修复方案:

方案一:通过参数传递变量(推荐)

这是Python函数间传递数据的标准方式,把x和y作为参数传给area2函数:

def main2():
    x = int(input("What is the length of your rectangle?:  "))
    y = int(input("What is the width of your rectangle?:  "))
    # 矩形面积不需要height,删掉z的输入
    print(area2(x, y))

def area2(length, width):
    return length * width

if __name__ == "__main__":
    main2()

解释:

  • 调用area2(x, y)时,把main2里的x、y值传递给area2的参数length、width
  • 删掉了没用的z变量,消除未使用变量的警告

方案二:使用全局变量(不推荐,仅作了解)

如果你暂时想简化写法,可以把x、y声明为全局变量,但这种方式会让代码逻辑混乱,不建议在实际项目中使用:

def main2():
    global x, y
    x = int(input("What is the length of your rectangle?:  "))
    y = int(input("What is the width of your rectangle?:  "))
    print(area2())

def area2():
    global x, y
    return x * y

if __name__ == "__main__":
    main2()

内容的提问来源于stack exchange,提问作者Benjamin Young

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 11:48:12