python中的多个IF语句

时间:2016-12-08 05:39:40

标签: python python-2.7 if-statement

我正在尝试在特定单元格中打印内容。我知道在将内容提取到输出之前要检查的单元格。我正在使用多个IF语句:

if lineCount == 5:
    if line[0]:
        print line[0], 'A5'
        OPfound = 1
        break
    if line[1]:
        print line[1], 'B5'
        OPfound = 1
        break
if lineCount == 4:
    if line[0]:
        print line[0], 'A4'
        OPfound = 1
        break
    if line[1]:
        print line[1],'B4'
        OPfound = 1
        break

输出格式如下: - 提取的内容,单元格编号

我要做的是首先检查A5中是否有任何内容 - 如果有内容然后提取它...否则检查B5中的内容 - 如果有内容则提取它...否则检查内容在A4

我得到B5和A4的输出......但不是A5

如果A5,B5和A4中没有内容,我如何检查B4中的内容......

3 个答案:

答案 0 :(得分:1)

break不允许您离开if条款,如果那是您确实试图突破的条款。这里的诀窍是删除break语句,并将if替换为elif,如下所示:

if lineCount == 5:
    if line[0]:
        print line[0],'A5'
        OPfound = 1
    elif line[1]:
        print line[1],'B5'
        OPfound = 1
if lineCount == 4:
    if line[0]:
        print line[0],'A4'
        OPfound = 1
    elif line[1]:
        print line[1],'B4'
        OPfound = 1

这样,如果第一个失败的话,你只会在每个lineCount子句中运行第二个if语句,而不是每次都失败。

答案 1 :(得分:1)

首先,您不能使用break结束Python代码块。当Python看到你缩进时会结束一个代码块,如下所示:

if condition: //or any other statement that needs a block
    //code goes here
//end of block

break语句用于终止它可以找到的最内层循环。如果您在循环中运行该代码,break语句可能会产生一些严重的错误。

无论如何,有一种更常规的方法可以测试多种情况。没有break语句的当前设置应该有效,但我建议您使用if...elif...else语句。这是格式:

if condition:
    //run if true
elif condition:
    //run if first expression was false, and this is true
elif condition:
    //run if second expression was false, and this is true

... (you get the idea)

else:
    //run if all other expressions are false

请记住,在Python找到一个在这样的语句中为真的表达式之后,它将运行相应的代码块并忽略所有其他块。

希望这有帮助!

答案 2 :(得分:1)

Darian Moody在他的blog post

中为这一挑战提供了很好的解决方案
a = 1
b = 2
c = True

rules = [a == 1,
         b == 2,
         c == True]

if all(rules):
    print("Success!")

当给定iterable中的所有元素都为true时,all()方法返回True。如果没有,则返回False

您可以在python docs here中阅读 little 更多信息,以及更多信息和示例here

(我也在这里回答了类似的问题 - How to have multiple conditions for one if statement in python