【问题标题】:Python 2 while loop fails in second iterationPython 2 while 循环在第二次迭代中失败
【发布时间】:2020-04-03 10:55:15
【问题描述】:

我创建了一个程序,要求用户猜测温度(空间温度),然后计算该温度的黑体光谱,并返回均方根偏差与测量数据的关系。然后要求用户再次猜测:

这是输入的代码,因为我还不能嵌入图像:

while True:
  temperature_guess = input("What is the temperature of the black body spectrum of space (in kelvin)?\
  Type 'stop' when you're happy with your estimate.")

  if temperature_guess == "stop":
    break

  else:
    T_guess = float(temperature_guess)

    print T_guess

    # Calculate intensities produced from measured wavelengths and user guess temperature

    intensities_guess=radiation(measured_lambda_metres,T_guess)

    print intensities_guess

    # Calculate root mean square deviation from measured values

    rmsd = rmsd(measured_intensity, intensities_guess)

    print "For your guessed temperature of" , T_guess , "kelvin, \
    the root mean square deviation from measured intensity data is" , "%.4g" %rmsd , \
    "to 4 significant figures."

程序在一次迭代中运行良好(一个温度猜测),如果我告诉它停止它会很好地中断,但如果我输入另一个温度,它会在中途停止。我可以从打印命令中看到它接受温度输入并基于此计算强度,但在均方根偏差计算中失败。

不知何故,“rmsd”函数不喜欢它第二次看到的东西。为什么会这样做?为什么要停在中间?

【问题讨论】:

  • 你用的是python2吗?在这种情况下,停下来!请改用 Python3。正式不再支持 Python2。

标签: python while-loop


【解决方案1】:

您似乎正在通过其返回值覆盖您的 rmsd 函数。在循环中使用不同的变量名,你不会有这个问题:

while True:
    # ...

    rmsd_value = rmsd(...)   # don't do rmsd = ... here, or you overwrite the function!

    # ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 2015-10-20
    相关资源
    最近更新 更多