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

如何在Python中跨函数使用变量并返回计算结果?

修复你的饮水量统计代码

原代码的核心问题是函数间变量传递错误和循环计数逻辑问题,以下是修正后的代码及关键说明:

问题分析

  • Calculate 函数无法直接访问 main 函数里的 intInput 和 intCalculate,因为变量有作用域限制,函数内部默认只能使用自己的局部变量。
  • 循环中输入 -999 时,i 仍会执行 +=1,导致天数统计多算一天。
  • Calculate 函数没有接收参数,也未正确实现累加逻辑。

修正后的代码

def main():
    total_ounces = 0
    days = 0
    while True:
        user_input = int(input("How many ounces of water did you drink each day? (输入-999结束统计)"))
        if user_input == -999:
            break
        days += 1
        total_ounces = calculate(total_ounces, user_input)
    
    print(f"You have drank {total_ounces} ounces of water")
    print(f"For {days} days")
    if days > 0:  # 避免除零错误
        average = total_ounces / days
        print(f"You drank an average of {average:.2f} ounces of water")
    else:
        print("No valid drinking data entered")

def calculate(current_total, daily_amount):
    # 接收当前总饮水量和当日饮水量,返回新的总饮水量
    return current_total + daily_amount

main()

关键修改点

  • 变量作用域与传参:calculate 函数接收两个参数 current_total(当前总饮水量)和 daily_amount(当日饮水量),计算后返回新的总水量,main 函数接收返回值更新 total_ounces,实现函数间的变量传递。
  • 循环逻辑优化:改用 while True + break 的结构,先判断输入是否为 -999,再统计天数,避免错误计数。
  • 命名规范:将变量名改为更具可读性的名称(如 intCalculate 改为 total_ounces),提升代码可维护性。
  • 异常处理:增加 days > 0 的判断,防止用户直接输入 -999 导致的除零错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:50:09