Python 2 while循环在第二次迭代中失败



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

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

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"函数不喜欢它第二次运行时看到的内容。它为什么要这么做?为什么要停在中间?

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

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

最新更新