如果声明没有正确比较

时间:2013-11-04 02:01:22

标签: python python-3.x

如上所述,我确定这是一个简单的错误,让我面对面,但我无法弄清楚为什么我的变量newState,当显式设置为字符串'F1'时,不会触发else条件如果:newState =='F1'......

我想我不需要移植这么多代码,抱歉。

 (EOL, LETTER, DIGIT, PERIOD, ILLEGAL_CHAR, LEGAL_CHAR) = range(0, 6)


STT = [ ['error', 1, 2, 0, 'error', 0], ['F1', 1, 1, 'F1', 'error', 'F1' ], 
['F2', 'F2', 2, 3, 'error', 'F2'], ['error', 'error', 4, 'error', 'error', 'error'],
['F3', 'F3', 4, 'F3', 'error', 'F3']  ]

for line in open("Sample.txt","r"):
    x1 = ''
    currState = 0
    newState = 'F1'
    for char in line:
        if newState != 'F1' or newState != 'F2' or newState != 'F3' or newState != 'error':
            currState = newState
            #If eol
            if char == '\n':
                response = EOL
                newState = STT[currState][response]
                break
            #if letter
            elif char.isalpha():
                x1 = x1 + char
                response = LETTER
                newState = STT[currState][response]
               # break
            #if Digit
            elif char.isdigit():
                x1 = x1 + char
                response = DIGIT
                newState = STT[currState][response]
            #if Period
            elif char == '.':
                x1 = x1 + char
                response = PERIOD
                newState = STT[currState][response]                       
            #If illegal char set
            elif (char == '~' or char == '?' or char == ':' or char == '_' or char == '\\' ):
                response = ILLEGAL_CHAR
                newState = STT[currState][response]
                break
                                           # elif x1 != '':  
                                                #response = 5
                                               # newState = STT[currState][response]
                                               # break
            #if any other legal char
            else:
                response = LEGAL_CHAR
                newState = STT[currState][response]        
        #We have a token
        else:
            getToken(newState, x1)

1 个答案:

答案 0 :(得分:3)

如果newstate为F1,则不会触发其他,因为newState != 'F2'会触发。

在第一个if中,尝试制作

if (not(newState == 'F1' or newState == 'F2' or newState == 'F3' or newState == 'error')):

问题是

if !A or !B or ...

不同
if !(A or B or...)

等于

if (!A and !B and ...)

DeMorgans法律。