不止一个if-else在单行中,如何解释它们?

时间:2016-10-22 18:10:55

标签: python python-3.x if-statement

嗯,我当然明白if-else是单行返回,如

return 0 if x==y else 1

哪个转换为

if x==y:
    return 0
else:
    return 1

我对那些if-else在一行中多次出现的陈述感到困惑,比如

def cmp(x, y):
    return 0 if x == y else 1 if x > y else -1

如何解释和理解用单行写的if-else语句。

2 个答案:

答案 0 :(得分:6)

引入括号使其更容易理解。

0 if x == y else 1 if x > y else -1
必须将

解析为

0 if x == y else (1 if x > y else -1)

答案 1 :(得分:3)

它嵌套了其他 - 如果为了清楚起见它可以被视为此

 if x == y:
     return 0
 else:
     if x > y: 
        return 1 
     else: 
        return -1

如果代码在不太可能的努力中清晰易懂,那就太棒了

所以稍后,如果你想在冗长的条件语句中添加一个案例然后它可能会出现问题,那么更好的选择是使用elif这样的梯子

def _comp(total):
    if total>90:
        return 'Python lover'
    elif total>80 and total<=89:
        return 'Friend of python'
  #     elif total>50 and total<=79      added later easily
  #         return 'you like python'     added later easily
    else:
        return 'python is waiting for you'