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

如何将一个def函数的变量传入另一个def函数并计算新总和?

如何在Python函数间传递变量并计算总和?

先修正原代码的几个问题

  1. 变量名拼写错误:原代码里的positve是拼写失误,正确应为positive,两个函数都需要修正。
  2. 重复导入模块:import random放在函数内部会导致每次调用函数时重复导入,建议移到文件最顶部。
  3. 参数被无意义覆盖:room1函数里的phone_charge参数被直接赋值为5,失去了参数的作用,改成可选参数更灵活。
  4. 返回字符串不利于计算:原函数返回字符串类型的电量值,后续无法直接做加法运算,应返回整数类型。

修正后的完整代码

import random

def room1(phone_charge=None):
    # 若未传入初始电量,默认设为5
    phone_charge = phone_charge if phone_charge is not None else 5
    rand_num = random.randint(1, 5)
    positive = phone_charge + rand_num
    print("An outlet! You quickly plug in your phone, but the wiring in the house is faulty and soon shorts out.\n")
    print(f"Your phone is now {positive} % charged\n")
    return positive

def room5(phone_charge):
    random_num = random.randint(1, 30)
    positive2 = phone_charge + random_num
    print(f"Your phone is now {positive2} % charged\n")
    return positive2

# 调用函数并传递变量
# 1. 获取room1的充电结果
charge_after_room1 = room1()
# 2. 将room1的结果传入room5,得到room5的充电结果
charge_after_room5 = room5(charge_after_room1)
# 3. 计算两个结果的总和
total_charge = charge_after_room1 + charge_after_room5
print(f"两次充电的电量总和是 {total_charge} %")

代码高亮的解决方法

确保代码块使用三个反引号包裹,并在开头指定语言为python,如上面的代码示例,主流markdown编辑器/平台都会正确识别并高亮代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:35:24