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

Python中如何在其他函数中使用read()函数的输入值?

解决函数间变量无法访问的问题

你的代码核心问题是变量作用域:函数内部定义的变量属于局部变量,只能在自身函数里使用,其他函数无法直接获取。比如read()里的foot、inch,calculate()里的转换结果,都没法被其他函数访问。

下面是两种修复方案,优先用第一种(更符合Python编码规范):

方案1:通过返回值传递数据

这种方式避免全局变量,代码更清晰易维护:

def read():
    foot = int(input("Foot?"))
    inch = int(input("Inch?"))
    # 返回获取到的两个输入值
    return foot, inch

def calculate(foot, inch):
    foot_to_meter = 0.3048 * foot
    foot_to_centimeter = foot_to_meter * 100  # 修正原代码错误:英尺转厘米应该乘以100
    inch_to_meter = 0.0254 * inch  # 修正原代码错误:正确英寸转米公式是1英寸=0.0254米
    inch_to_centimeter = inch_to_meter * 100
    # 返回四个计算结果
    return foot_to_meter, foot_to_centimeter, inch_to_meter, inch_to_centimeter

def write(foot, inch, foot_to_meter, foot_to_centimeter, inch_to_meter, inch_to_centimeter):
    print(f"The {foot} foot is {foot_to_meter} meter")
    print(f"The {foot} foot is {foot_to_centimeter} centimeter")
    print(f"The {inch} inch is {inch_to_meter} meter")
    print(f"The {inch} inch is {inch_to_centimeter} centimeter")

def main():
    # 接收read返回的输入值
    foot, inch = read()
    # 把输入值传给calculate,接收计算结果
    foot_m, foot_cm, inch_m, inch_cm = calculate(foot, inch)
    # 把所有需要打印的变量传给write
    write(foot, inch, foot_m, foot_cm, inch_m, inch_cm)

main()

改动说明:

  • read():添加return foot, inch,把用户输入的值传递出去
  • calculate():添加参数foot, inch接收输入数据,计算完成后返回四个转换结果
  • write():添加参数接收所有要打印的变量,用f-string让输出格式更整洁
  • 顺便修正了原代码里的单位转换错误,原公式的计算逻辑不符合标准单位换算规则

方案2:使用全局变量(不推荐)

如果一定要用全局变量,需要在函数内用global声明变量,但这种方式会让代码耦合度高,不利于后期维护和调试:

# 定义全局变量
foot = 0
inch = 0
foot_to_meter = 0
foot_to_centimeter = 0
inch_to_meter = 0
inch_to_centimeter = 0

def read():
    global foot, inch
    foot = int(input("Foot?"))
    inch = int(input("Inch?"))

def calculate():
    global foot_to_meter, foot_to_centimeter, inch_to_meter, inch_to_centimeter
    foot_to_meter = 0.3048 * foot
    foot_to_centimeter = foot_to_meter * 100
    inch_to_meter = 0.0254 * inch
    inch_to_centimeter = inch_to_meter * 100

def write():
    print(f"The {foot} foot is {foot_to_meter} meter")
    print(f"The {foot} foot is {foot_to_centimeter} centimeter")
    print(f"The {inch} inch is {inch_to_meter} meter")
    print(f"The {inch} inch is {inch_to_centimeter} centimeter")

def main():
    read()
    calculate()
    write()

main()

注意:

全局变量虽然实现简单,但如果函数数量增多,很容易因不小心修改变量值导致难以排查的bug,因此优先推荐方案1。

内容的提问来源于stack exchange,提问作者sina mostafidi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 20:43:10