多个 if 和 elif 之间的区别?
- 2025-02-11 09:50:00
- admin 原创
- 48
问题描述:
在 python 中,以下说法有区别吗:
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
和
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
只是想知道多个if
s 是否会导致任何不必要的问题,以及使用 s 是否是更好的做法elif
。
解决方案 1:
多个 if 意味着您的代码将检查所有的 if 条件,而在 elif 的情况下,如果一个 if 条件满足,它就不会检查其他条件。
解决方案 2:
另一个简单方法来查看 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 来说是正确的,因此打印“你是个孩子”。
第二个 if 语句为假,因此执行 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
解决方案 3:
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,这一点会更加明显。
解决方案 4:
这是另一种思考方式:
假设有两个特定情况,if/else catchall 结构无法满足要求:
例子:
我有一个 3 X 3 井字游戏板,我想打印两条对角线的坐标,而不是其余的方格。
我决定改用 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(' ' * 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(' ' * 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 是互斥的,在测试后实际上执行一个分支。
以用户2333594为例
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!"
解决方案 6:
在上面的例子中存在差异,因为您的第二个代码缩进了 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,因此 Python 解释器将elif视为语法错误。
解决方案 7:
当您使用多个 时if
,您的代码将返回每个if
语句以检查表达式是否符合您的条件。有时,会出现单个表达式发送许多结果的情况,这些结果甚至不是您预料到的。但是,elif
当表达式符合您的任何条件时,使用 会终止该过程。
解决方案 8:
以下是我分解控制流语句的方法:
# 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
因为前面的语句计算结果为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
因为所有前面的语句都无法执行
解决方案 9:
如果是:
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
,其前面的语句将被省略/不执行。