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

Python函数调用疑问:修改start_point后结果未更新的原因

问题分析与解决方案

嘿,我一眼就看出问题所在啦!你之所以第二次打印的结果没变化,核心原因是:你修改了start_point的值,但没有用新的start_point重新调用secret_formula()函数。

具体原因解释

当你第一次执行beans, jars, crates = secret_formula(start_point)时,beans、jars、crates这三个变量就被赋值为start_point=10000对应的计算结果了。之后你虽然把start_point除以10变成了1000,但并没有重新调用函数来计算新的数值——这三个变量会一直保留第一次的结果,自然不会跟着start_point的变化而更新。

修正后的代码

只需要在修改start_point之后,重新调用secret_formula()函数更新变量值就可以了:

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates

start_point = 10000
beans, jars, crates = secret_formula(start_point)
print(f"With a starting point of: {start_point}")
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")

start_point = start_point / 10
# 关键步骤:用新的start_point重新计算并更新变量
beans, jars, crates = secret_formula(start_point)
print("We can have also do that this way:")
print("We'd have {} beans, {} jars, and {} crates.".format(beans, jars, crates))

修正后的运行结果

With a starting point of: 10000
We'd have 5000000 beans, 5000.0 jars, and 50.0 crates.
We can have also do that this way:
We'd have 500000 beans, 500.0 jars, and 5.0 crates.

这样就完全符合你的预期啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:17:55