1

我试图创建的代码是根据输入的波长值打印波长,例如无线电波或微波。

    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 命令。

4

5 回答 5

4

你想在这里使用 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-12T23:35:22.180 回答
0

元组列表在这里可以很好地工作:

wave_categories = []

# Load up your data of definitions
wave_categories.append((1e-3, 'Microwaves'))
wave_categories.append((1e-2, 'Somewaves'))
wave_categories.append((1e-1, 'Radiowaves'))
wave_categories.append((1, 'Ultrawaves'))

然后你的检测就变成了一个循环:

def find_wave(wavelength):
    for category_wavelength, name in wave_categories:
        if wavelength < category_wavelength:
            return name
    raise Exception('Wavelength {} not detected in list'.format(wavelength))

要使其适用于大量类别,只需将更多数据添加到wave_categories.

于 2013-09-12T23:36:00.693 回答
0

对于少数“中断值”,您的方法没有错。对于大量“中断值”,您最好创建一个包含中断值和相应操作的表。

即,在您的情况下,是带有波长和分类的表格。第一行包含 10e-1 和“无线电波”,第二行包含 10e-3 和“微波”

在代码中,您只需循环直到找到waveValue 的正确行。

这在税表中很常见。作为奖励,您可以将税表存储在外部数据库中,而不是在程序中对值进行硬编码。

于 2013-09-12T23:31:30.177 回答
0

我认为你的第二个说法是错误的。

它说 waveValue >10*-1<10*-3 我认为是 >-10 和 < -30 如果我说的是正确的,那么不能有大于 -10 的数字小于 -30

于 2013-09-12T23:32:26.257 回答
0

您可以为此使用该bisect模块:

from bisect import bisect
freqs = [10**-11,  10**-8, 4*10**-7, 7*10**-7, 10**-3, 10**-1]
names = ['Gamma rays', 'X-rays', 'Ultraviolet', 'Visible light', 
         'Infared', 'Microwaves', 'Radio Waves']
>>> names[bisect(freqs, 10**-2)]
'Radio Waves'
>>> names[bisect(freqs, 10**-4)]
'Microwaves'
于 2013-09-13T18:14:45.987 回答