3

python else的小九九

 1 year ago
source link: https://blog.51cto.com/coderusher/5722548
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Table of Contents

elsepython语言中活生生的备胎,谁都是想用就用,不用也行

1.if else语句

常规的if...else语句我就不过多赘述了,这里提一下三元表达式,可以 有效减少代码量 ,使代码的整体逻辑更为清晰明了。

常规语句:

if conditions:
	func1()
else:
	func2()

使用三元表达式后:

# 条件满足时执行func1,条件不满足时执行func2
func1() if conditions else func2()

2.for else 语句

for...else 的执行逻辑是:如果for循环正常结束,则执行else中语句,注意如果 for 循环中嵌有 break 等导致for无法执行完毕,则 else 中的内容就不会执行,常用于设置flag上面,如果循环过程中出现满足条件的情况就将flag设置为True,反之则为False,也可以有效减少代码量。

# 遍历
for item in container:
 	# 判断条件是否满足
	if search_something(item):
        	# 条件满足,执行相关语句并跳出循环
		process(item)
		break
else:
	# 遍历完并没有满足条件的情况,执行else语句
	not_found_in_container()

3.try else语句

正确的讲,应该是try... except... else...finally... 语句,常常用于捕捉异常

try:
    process()
    print("try语句运行正常")
except Exception as e:
    # 捕捉异常类型
    print("try运行异常,捕捉到的异常为:", e)
else:
    # 在无异常时执行else语句
    print("try语句运行正常")
finally:
    # 最后执行的语句
    print("最后执行的语句")

这里顺带再提一下常用于异常处理的raise模块和assert语句。

3.1 raise

当程序出现错误会自动引发异常,当然也可以通过raise显式引发异常。raise语句执行后,raise后的语句将不会执行。

  • raise 语句有如下三种常用的用法:
    1.raise:单独一个 raise。该语句引发当前上下文中捕获的异常(比如在 except 块中),或默认引发 RuntimeError 异常。
    2.raise 异常类:raise 后带一个异常类。该语句引发指定异常类的默认实例。
    3.raise 异常对象:引发指定的异常对象。
try:
    1/0
except Exception:
    raise NameError("变量未定义") from Exception

3.2 assert

在一个程序还未完善之前,与其让它在运行时才崩溃,不如在我们觉得可能出现异常的地方添加assert语句,使得其在满足错误条件时就提前崩溃,提高我们的码力。

def func():
	process()
	# 如果conditions条件确实满足,则返回1,反之则输出异常
	assert conditions
	return 1

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK