51Testing软件测试论坛
标题:
python中的else语句
[打印本页]
作者:
测试积点老人
时间:
2018-12-19 13:16
标题:
python中的else语句
python中的for和while循环支持else分支,else中的代码只有在没有break的情况下运行,如下:
def contains(haystack, needle):
"""
Throw a ValueError if `needle` not
in `haystack`.
"""
for item in haystack:
if item == needle:
break
else:
# The `else` here is a
# "completion clause" that runs
# only if the loop ran to completion
# without hitting a `break` statement.
raise ValueError('Needle not found')
>>> contains([23, 'needle', 0xbadc0ffee], 'needle')
None
>>> contains([23, 42, 0xbadc0ffee], 'needle')
ValueError: "Needle not found"
复制代码
其实上有时候用raise也能实现相似功能,如下:
def better_contains(haystack, needle):
for item in haystack:
if item == needle:
return
raise ValueError('Needle not found')
复制代码
这样更符合python风格。
if needle not in haystack:
raise ValueError('Needle not found')
复制代码
作者:
Miss_love
时间:
2021-1-5 17:01
支持分享
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/)
Powered by Discuz! X3.2