Python IF / ELIF语句

时间:2015-11-21 17:40:53

标签: python if-statement

好吧因为某些原因if语句有效,但elif没有...不确定原因,没有语法或缩进错误,脚本运行正常但是它不会使用elif,就好像它没有被写过一样......

代码示例:

try:
    if '120' in resp.read():
        print '120'
        self.write_to_file('120' '\n')
        return True
    elif '130' in resp.read():
        print '130'
        self.write_to_file('130' '\n')
        return True
    else:
        print 'no number'
        return False
except:

2 个答案:

答案 0 :(得分:3)

您应该阅读单次,然后再与读取的值进行比较:

try:
    value = resp.read()
    if '120' in value:
        print '120'
        self.write_to_file('120' '\n')
        return True
    elif '130' in value:
        print '130'
        self.write_to_file('130' '\n')
        return True
    else:
        print 'no number'
        return False
except:
    # do something here!
    print('error')

答案 1 :(得分:1)

使用resp.read()一次将完全读取响应,因此后续调用resp.read()将不会产生任何输出。

您需要先将输出存储在变量中,然后再次检查变量而不是响应:

response = resp.read()
if '120' in response:
    print '120'
    self.write_to_file('120' '\n')
    return True
elif '130' in response:
    print '130'
    self.write_to_file('130' '\n')
    return True
else:
    print 'no number'
    return False
相关问题