在python中,说:
之间有区别吗?if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
和
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
只是想知道多个if
是否会导致任何不必要的问题,以及是否更好的做法是使用elif
。
答案 0 :(得分:71)
多个if表示你的代码会检查所有if条件,如果是elif,如果条件满足则不会检查其他条件..
答案 1 :(得分:28)
另一种简单的方法可以看出使用if和elif之间的区别就是这个例子:
def analyzeAge( age ):
if age < 21:
print "You are a child"
if age >= 21: #Greater than or equal to
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
analyzeAge( 18 ) #Calling the function
>You are a child
>The age must be a positive integer!
在这里你可以看到,当18用作输入时,答案是(令人惊讶的)2个句子。那是错的。它应该只是第一句话。
那是因为BOTH if语句正在被评估。计算机将它们视为两个单独的陈述:
elif 解决了这个问题,并使两个if语句“粘在一起”为一个:
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!"
analyzeAge( 18 ) #Calling the function
>You are a child
答案 2 :(得分:8)
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略快一些。如果有更多的ifs和更多的elifs,这将更加明显。
答案 3 :(得分:3)
以下是另一种思考方式:
假设您有两个特定的条件,即if / else catchall结构是不够的:
示例:
我有一个3 X 3 tic-tac-toe板,我想要打印两个对角线的坐标,而不是其余的正方形。
我决定使用和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)
但是等等!我想包括diagonal2的所有三个坐标,因为(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)
最终知道您想要实现的类型或结果将决定您编码的条件关系/结构的类型。
答案 4 :(得分:2)
在上面的示例中存在差异,因为您的第二个代码缩进了 elif ,它实际上位于 if 块中,并且在语法和逻辑上都是错误的在这个例子中。
Python使用行缩进来定义代码块(大多数C类语言使用{}来封装代码块,但python使用行缩进),因此在编码时,应该认真考虑缩进。
你的样本1:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
如果和 elif 缩进相同,那么它们与相同的逻辑相关。 你的第二个例子:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
elif 在 if 之前缩进,在另一个块包围它之前,因此在 if 块中考虑它。并且由于 if 内部没有其他嵌套 if ,因此 elif 被Python解释器视为语法错误。
答案 5 :(得分:1)
elif
只是表达else: if
,
多个ifs在测试后执行多个分支,而elifs是相互排他的,在测试后执行一个分支。
参加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!"
答案 6 :(得分:0)
当您使用多个docx
时,您的代码将返回到每个if
语句中,以检查该表达式是否适合您的条件。
有时,有时会为单个表达式发送许多结果,而这甚至是您无法期望的。
但是,当表达式适合您的任何条件时,使用if
会终止该过程。
答案 7 :(得分:0)
这是我分解控制流语句的方式:
# 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
,因为 all 前面的语句无法执行
答案 8 :(得分: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
时,前面的语句将被省略/不执行。