Elif-row没有其他python

时间:2014-06-15 15:05:17

标签: python if-statement

是否可以在else行的末尾写一个if,如果所有if语句都不成立则只会执行?例如:

if foo==5:
    pass
if bar==5:
    pass
if foobar==5:
    pass
else:
    pass

在此示例中,如果foobar不是5,则会执行else部分,但如果foobarfoobar为'{1}},我希望执行该部分t 5.(但是,如果所有陈述都是真的,则所有陈述都必须执行。)

5 个答案:

答案 0 :(得分:4)

做这样的事情怎么样?如果运行其他三个中的一个,则运行四个if语句但不会运行第四个if语句,因为其他语句更改了变量key

key = True

if foo == 5:
    key = False
if bar == 5:
    key = False
if foobar == 5:
    key = False
if key:
    pass # this would then be your else statement

答案 1 :(得分:2)

不直接 - 这三个if块是分开的。你可以使用嵌套,但这会非常复杂;实现这一目标的最好方法可能是:

if foo == 5:
    ...
if bar == 5:
    ...
if foobar == 5:
    ...
if not any((foo == 5, bar == 5, foobar == 5)):
    ...

答案 2 :(得分:2)

我认为没有任何过于优雅的方式可以用Python或任何其他语言来做到这一点。您可以将值存储在列表中,但这会混淆实际测试ifs,例如

tests = [bar ==4, foo == 6, foobar == 8]

if tests[0] :
  # do a thing
if tests[1] :
  # Make a happy cheesecake
if tests[2] :
  # Oh, that's sad

if not True in tests :
  # Invade Paris

或者您可以设置跟踪标记

wereAnyTrue = False

if foo == 4 :
  # Do the washing
  wereAnyTrue = True
if bar == 6 :
  # Buy flowers for girlfriend
  wereAnyTrue = True

# ... etc

if not wereAnyTrue :
  # Eat pizza in underpants

答案 3 :(得分:0)

jonrsharpe的答案的变体将是使用链式相等测试。像这样:

if foo != bar != foobar != 5:
    #gets executed if foo, bar and foobar are all not equal to 5

看起来有点好笑,我想你应该决定哪一个更具可读性。并且,显然,如果其中一个变量应该等于不同的东西,这将不会起作用。

编辑:哎呀,这不会奏效。例如 1 != 1 != 3 != 5 返回false,而 1 != 2 != 3 != 5 返回true。遗憾

答案 4 :(得分:0)

如果所有if 5 in (foo, bar, foobar): pass else: pass 语句都用于检查相同的值,我将使用以下格式。这将使代码更短,更易读,IMO

if (listBox1.SelectedIndex < listBox1.Items.Count - 1)
{
    listBox1.SelectedIndex += 1;
}
else
{
    listBox1.SelectedIndex = 0;
}