Skip to main content
 首页 » 编程设计

Python 3.x 函数值不正确

2025年05月04日21lvdongjie

我不明白为什么我的代码会给我错误的值。作为 Python 的初学者,我正在学习 def()。

所以我的代码是:

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 
 
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 5000000 beans, 5000.0 jars, and 50.0 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 jars, and 5 crates.

类似的东西...因为 start_point = start_point/10 对吗?

我做错了什么?

Obs:是的,出于测试原因,我使用了不同的方法来“打印”。

请您参考如下方法:

你需要像这样记忆secret_formula():

start_point = start_point / 10 
beans, jars, crates = secret_formula(start_point) 

测试代码:

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 
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.0 beans, 500.0 jars, and 5.0 crates.