简体   繁体   English

Python IF/ELIF 语句

[英]Python IF/ELIF statement

Okay so for some reason if statement works, but elif doesn't.. not sure why, there's been no syntax or indentation errors, script runs fine however it doesn't use elif as if it wasn't written..好吧,出于某种原因, if语句有效,但elif没有……不知道为什么,没有语法或缩进错误,脚本运行良好,但它不使用elif就好像它没有写一样……

example of code:代码示例:

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:

You should read a single time and after that do the comparisons with the value that was read:您应该阅读一次,然后与读取的值进行比较:

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')

Using resp.read() once will read the response completely, so subsequent calls of resp.read() will not yield any output.使用resp.read()一次将完全读取响应,因此resp.read()后续调用不会产生任何输出。

You need to store the output in a variable first, and then check on the variable instead of the response again:您需要先将输出存储在变量中,然后再次检查变量而不是响应:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM