我的程序没有正确比较python中的值

时间:2014-10-06 21:26:24

标签: python

我编写了这段代码,它应该将这些行值与标称值进行比较。用户应输入一个百分比值,将lineValue与标称值进行比较。如果lineValue在给定标称值的百分比范围内,它将传递为真。

我的程序只有在lineValue数字正好是名义价值时才会返回true。即使它在用户输入的百分比范围内,所有其他值也都是失败的。有没有人在我的代码中看到一个错误,以防止数字被注册为真?

nominalValue=470
print "Nominal Resistor Value: " , nominalValue
lineValue = [470, 358, 324, 234, 687,460]


user_Input=raw_input("Please Enter a Tolerance %: ")
if user_Input.isdigit():
    tolerance = int(user_Input)
    if tolerance <=20 and tolerance >=1:
        print "Tolerance Level:", user_Input
        percentageHigh = (tolerance/100.0 + 1.00)
        percentageLow = (1.00 - tolerance/100.0)
        print percentageHigh
        print percentageLow
        highNominal = nominalValue*percentageHigh
        lowNominal = nominalValue*percentageLow
        print highNominal
        print lowNominal
        for seriesInput in lineValue:
            if (percentageHigh*seriesInput) <= highNominal and (percentageLow*seriesInput) >= lowNominal:           
                print seriesInput,"Pass"
                print percentageHigh*seriesInput

            else: 
                print seriesInput,"Fail"
                print percentageLow*seriesInput
    else:
        print "Please enter a value between 1-20"
else:
    print "Please enter a number for a percent value"

3 个答案:

答案 0 :(得分:2)

你已经计算过highNominal和lowNominal,所以你想要这一行:

if seriesInput <= highNominal and seriesInput >= lowNominal:           

或@GregHewgill指出:

if lowNominal <= seriesInput <= highNominal:

答案 1 :(得分:1)

您当前的代码询问:

if (percentageHigh*seriesInput) <= highNominal and 
   (percentageLow*seriesInput)  >= lowNominal:

但是

highNominal = nominalValue*percentageHigh
lowNominal = nominalValue*percentageLow

所以你的比较相当于:

if (percentageHigh*seriesInput) <= nominalValue*percentageHigh and 
   (percentageLow*seriesInput)  >= nominalValue*percentageLow:

简化为:

if seriesInput <= nominalValue and 
   seriesInput => nominalValue:

通过这种方式可以清楚地看到,只有在seriesInput == nominalValue时才会出现这种情况,因为seriesInput不能大于和小于{{1> }}!

答案 2 :(得分:1)

在你的支票

if (percentageHigh*seriesInput) <= highNominal and (percentageLow*seriesInput) >= lowNominal:

您正在检查seriesInput的范围是否在标称值附近的范围内,根据定义它永远不会。您只想检查seriesInput的是否在nominalValue附近的范围内,如此

if seriesInput <= highNominal and seriesInput >= lowNominal:

更直观地说,你正在检查:

nominalValue range
|-----x-----|

seriesInput range, never going to be inside the nominalValue range
    |----y----|

seriesInput value, within range of nominalValue
|-----x--y--|