Skip to main content
 首页 » 编程设计

python之`elif` 执行的任务不能由 'if' 完成

2025年05月04日13lidabo

假设一个最小的控制流情况:

    x = input("Numaral:  ") 
    y = input("Numaral:  ") 
    if x < y: 
        print('x is less than y.') 
    elif x > y: 
        print('x is greater than y.') 
    else: 
        print('x is equal to y.') 

跑过去

    $ python3 draft.py 
    Numaral:  3 
    Numaral:  3 
    x is equal to y. 

当用if替换elif时

    x = input("Numaral:  ") 
    y = input("Numaral:  ") 
    if x < y: 
        print('x is less than y.') 
    if x > y: 
        print('x is greater than y.') 
    else: 
        print('x is equal to y.') 

逻辑还是完全正确的。

    $ python3 draft.py 
    Numaral:  4 
    Numaral:  2 
    x is greater than y. 

我搜索并阅读了区分if和elif的答案,
似乎这些论点并没有切中要害,无法说服 elif 存在的必要性,因为 elif 可以直接替换为 if或间接。

是否存在控制流逻辑只能由 elif 或
如果 elif 不存在,则控制流有缺陷。

请您参考如下方法:

elif只是表达 else: if 的一种好方法,但这意味着你的等价是错误的:

if x < y: 
    print('x is less than y.') 
if x > y: 
    print('x is greater than y.') 
else: 
    print('x is equal to y.') 

评估if x > y测试即使它已经采取了 x < y分支。使用 elif允许您表达您知道这些分支是相互排斥的(对于 < 的合理定义),因此代码应该是

if x < y: 
    print('x is less than y.') 
else: 
    if x > y: 
        print('x is greater than y.') 
    else: 
        print('x is equal to y.') 

您可以看到它的可读性如何降低,并且使用 long elif 时的扩展性非常差链(提供深层嵌套代码)。

举一个互斥属性更重要的例子,考虑类似的东西

if x == None: 
    print "x is None" 
elif x.method() < 42: 
    print "x is not None, and method() is < 42" 
else: 
    print "x is not None but method() >= 42" 

在哪里替换 elif与 if会引发异常(如果 x 真的是 None ,你不能调用它的方法)