正确的处理 if else 的方法
Correct way to treat if else with no else to do
假设我有一个 if
子句在 condition == True
时做某事,而在 False
时什么都不做。我可以想到三种表达方式:省略 else
语句,如下所示:
beginning of code
if condition == True:
do something
rest of the code
明确告诉 python 什么都不做:
beginning of code
if condition == True:
do something
else:
pass
rest of the code
另一个可能不太好的实践版本重复了其余代码:
if condition == True:
do something
rest of the code
else:
rest of the code
第一个肯定更短,但是其中一个比另一个更有效吗?除了清晰度之外,这些代码之间还有其他区别吗?
你的第二个例子更清楚地表达了你想要的,假设你确实希望 rest of code
无论如何都被执行。
假设我有一个 if
子句在 condition == True
时做某事,而在 False
时什么都不做。我可以想到三种表达方式:省略 else
语句,如下所示:
beginning of code
if condition == True:
do something
rest of the code
明确告诉 python 什么都不做:
beginning of code
if condition == True:
do something
else:
pass
rest of the code
另一个可能不太好的实践版本重复了其余代码:
if condition == True:
do something
rest of the code
else:
rest of the code
第一个肯定更短,但是其中一个比另一个更有效吗?除了清晰度之外,这些代码之间还有其他区别吗?
你的第二个例子更清楚地表达了你想要的,假设你确实希望 rest of code
无论如何都被执行。