Python if语句带有多个子句

时间:2013-09-12 23:21:28

标签: python python-3.x

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

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

5 个答案:

答案 0 :(得分: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")

答案 1 :(得分:0)

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

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

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

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

答案 2 :(得分:0)

我认为你的第二个陈述是错误的。

它表示waveValue> 10 * -1 <10 * -3,我认为&gt; -10&lt; -30如果我说的是正确的话,那么大于-10的数字不能小于-30

答案 3 :(得分: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添加更多数据。

答案 4 :(得分: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'
相关问题