多个if和elif的区别?

问题描述 投票:0回答:9

在Python中,说:

之间有区别吗?
if text == 'sometext':
    print(text)
if text == 'nottext':
    print("notanytext")

 if text == 'sometext':
        print(text)
 elif text == 'nottext':
        print("notanytext")

只是想知道多个

if
是否会导致任何不必要的问题,以及使用
elif
是否是更好的做法。

python if-statement
9个回答
176
投票

多个if意味着你的代码会去检查所有的if条件,就像elif的情况一样,如果一个if条件满足它就不会检查其他条件..


70
投票

查看 if 和 elif 使用差异的另一种简单方法是这里的示例:

# According to the UN Convention of the Rights of the Child
ADULT_AGE = 18
def analyze_age(age):
   if age < ADULT_AGE and age > 0:
       print("You are a child")
   if age >= ADULT_AGE:
       print("You are an adult")
   else:
       print("The age must be a positive integer!")

analyze_age(16)
>You are a child
>The age must be a positive integer!

在这里你可以看到,当使用 18 作为输入时,答案是(令人惊讶的)2 个句子。那是错的。应该只是第一句话。

这是因为两个 if 语句都在被评估。计算机将它们视为两个单独的语句:

  • 第一个对于 18 来说是正确的,所以打印出“You are a child”。
  • 第二个 if 语句为 false,因此 else 部分为 执行打印“年龄必须是正整数”。

elif 解决了这个问题,并使两个 if 语句“粘在一起”为一个:

def analyze_age(age): if age < ADULT_AGE and age > 0: print("You are a child") elif age >= ADULT_AGE: print("You are an adult") else: print("The age must be a positive integer!") analyze_age(16) >You are a child
    

15
投票
def multipleif(text): if text == 'sometext': print(text) if text == 'nottext': print("notanytext") def eliftest(text): if text == 'sometext': print(text) elif text == 'nottext': print("notanytext") text = "sometext" timeit multipleif(text) 100000 loops, best of 3: 5.22 us per loop timeit eliftest(text) 100000 loops, best of 3: 5.13 us per loop

可以看到elif稍微快一些。如果有更多的 if 和 elif,这一点会更加明显。


5
投票
这是思考这个问题的另一种方式:

假设您有两个特定条件,if/else 包罗万象的结构是不够的:

示例:

我有一个 3 X 3 井字游戏板,我想打印两条对角线的坐标,而不是其余方块的坐标。

Tic-Tac-Toe Coordinate System

我决定改用 and if/elif 结构...

for row in range(3): for col in range(3): if row == col: print('diagonal1', '(%s, %s)' % (i, j)) elif col == 2 - row: print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))

输出为:

diagonal1 (0, 0) diagonal2 (0, 2) diagonal1 (1, 1) diagonal2 (2, 0) diagonal1 (2, 2)

但是等等!我想包含对角线 2 的所有三个坐标,因为 (1, 1) 也是对角线 2 的一部分。

“elif”导致了与“if”的依赖关系,因此,如果满足原始“if”,则即使“elif”逻辑也满足条件,“elif”也不会启动。

让我们将第二个“elif”更改为“if”。

for row in range(3): for col in range(3): if row == col: print('diagonal1', '(%s, %s)' % (i, j)) if col == 2 - row: print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))

我现在得到了我想要的输出,因为两个“if”语句是互斥的。

diagonal1 (0, 0) diagonal2 (0, 2) diagonal1 (1, 1) diagonal2 (1, 1) diagonal2 (2, 0) diagonal1 (2, 2)

最终知道您想要实现什么类型或结果将决定您编码的条件关系/结构类型。


5
投票

elif

只是一种奇特的表达方式
else: if

多个if测试后执行多个分支,而elif互斥,测试后实际执行一个分支。

以user2333594为例

def analyzeAge( age ): if age < 21: print "You are a child" elif age > 21: print "You are an adult" else: #Handle all cases were 'age' is negative print "The age must be a positive integer!"

可以改写为:

def analyzeAge( age ): if age < 21: print "You are a child" else: if age > 21: print "You are an adult" else: #Handle all cases were 'age' is negative print "The age must be a positive integer!"

另一个例子可能是:

def analyzeAge( age ): if age < 21: print "You are a child" else: pass #the if end if age > 21: print "You are an adult" else: #Handle all cases were 'age' is negative print "The age must be a positive integer!"
    

3
投票
在上面的示例中存在差异,因为您的第二个代码缩进了

elif,它实际上位于 if 块内,并且在本例中在语法和逻辑上都是错误的。

Python 使用行缩进来定义代码块(大多数类似 C 的语言都使用 {} 来包围代码块,但 Python 使用行缩进),因此在编码时应该认真考虑缩进。

您的样品 1:

if text == 'sometext': print(text) elif text == 'nottext': print("notanytext")

if

elif缩进相同,因此它们与相同的逻辑相关。 你的第二个例子: if text == 'sometext': print(text) elif text == 'nottext': print("notanytext")

在另一个块将其包围之前,
elif

if 缩进得更多,因此它被视为位于 if 块内。并且由于 if 内部没有其他嵌套 if,因此 elif 被 Python 解释器视为语法错误。


1
投票
if

时,您的代码将返回到每个

if
语句中以检查表达式是否适合您的条件。 有时,有时会为单个表达式发送许多结果,这是您意想不到的。 但是,当表达式适合您的任何条件时,使用
elif
会终止该过程。
    


1
投票

# if: unaffected by preceding control statements def if_example(): if True: print('hey') if True: print('hi') # will execute *even* if previous statements execute
将打印 
hey

hi

# elif: affected by preceding control statements def elif_example(): if False: print('hey') elif True: print('hi') # will execute *only* if previous statement *do not*
将打印 
hi

only
因为前面的语句评估为 False

# else: affected by preceding control statements def else_example(): if False: print('hey') elif False: print('hi') else: print('hello') # will execute *only* if *all* previous statements *do not*
将打印
hello

,因为

all
前面的语句未能执行


0
投票
情况:

if text == 'sometext': print(text) if text == 'nottext': print("notanytext")

即使只有第一个 
if

语句是

if
,也会执行同一缩进级别的所有
True
语句。

情况:

if text == 'sometext': print(text) elif text == 'nottext': print("notanytext")

if

语句为

True
时,前面的语句将被省略/不执行。
    

© www.soinside.com 2019 - 2024. All rights reserved.