我试图创建的代码是根据输入的波长值打印一个波长,例如无线电波或微波。
userInput = input("Enter wavelength (m) value: ")
waveValue= float(userInput)
if waveValue > 10**-1 :
print("Radio Waves")
elif waveValue < 10**-3 :
print("Microwaves")
elif waveValue < 7*10**-7 :
print("Infared")
elif waveValue <4-10**-7 :
print(" Visible light")
elif waveValue <10**-8 :
print( "Ultraviolet")
elif waveValue <10**-11 :
print( "X-rays")
elif waveValue >10**-11 :
print("Gamma rays")
else :
print()关于如何使第二个if语句工作的任何提示。我输入的每一个输入都输出无线电波,因为我的论点不能正常工作。
此外,还有5个输入,我将不得不使用elif命令。
发布于 2013-09-12 23:35:22
你是在用10的力量吗?因为"10到负1“的惯例是1.0e-1。您的代码中包含的内容可以转换为"10倍-1“或-10倍,我认为这不是您想要的。
我将改写为:
if waveValue > 1.0e-1:
print("Radio Waves")
elif (waveValue > 1.0e-3) and (waveValue < 1.0e-1):
print("Micro Waves")正如先前的答案所指出的那样,排序答案的效率也更高,这样就不需要进行比较(这些值已经被早期的测试考虑到了)。
例如:
if waveValue < 1.0e-3:
<not in current code>
elif waveValue < 1.0e-1:
print("Micro Waves")
else:
print("Radio Waves")发布于 2013-09-12 23:31:30
对于少量的“破坏值”,您的方法没有什么问题。对于大量的“中断值”,最好创建一个表,其中包含断点值和相应的操作。
也就是说,在你的情况下,一个有波长和分类的表格。第一行包含10e-1和“无线电波”,第二排包含10e-3和“微波”。
在代码中,只需循环遍历直到找到waveValue的正确行为止。
这在纳税表中很常见。作为奖励,您可以将您的纳税表存储在外部数据库中,而不是对程序中的值进行硬编码。
发布于 2013-09-12 23:32:26
我认为你的第二种说法是错误的。
它说waveValue >10*-1<10*-3,我认为是>-10和< -30,如果我说的是正确的,那么就不可能有大于-10的小于-30的数字。
https://stackoverflow.com/questions/18775823
复制相似问题