第9条:避免for~else 语法
Item 9: Avoid else Blocks After for and while Loops
Python具有循环后else的特殊语法。
for xxx:
do_something
else:
some_statements
else块会在循环没有被break时执行。
不推荐这种语法,这里大家看看就行,如果别人写了我们看得懂就行。
正常结束循环,没有break,else块执行:
for i in range(3):
print('Loop', i)
else:
print('Else block!')
>>>
Loop 0
Loop 1
Loop 2
Else block!
break发生,else块不会执行:
for i in range(3):
print('Loop', i)
if i == 1:
break
else:
print('Else block!')
>>>
Loop 0
Loop 1
下面看一个for~else
的例子:
判断互质数:如果循环结束都没有发现共同约数,那么a,b互质。:
a = 4
b = 9
for i in range(2, min(a, b) + 1):
print('Testing', i)
if a % i == 0 and b % i == 0:
print('Not coprime')
break
else:
print('Coprime')
>>>
Testing 2
Testing 3
Testing 4
Coprime
但是可以有更直观的写法:helper函数
def coprime(a, b):
for i in range(2, min(a, b) + 1):
if a % i == 0 and b % i == 0:
return False
return True
assert coprime(4, 9)
assert not coprime(3, 6)
或者使用结果变量
def coprime_alternate(a, b):
is_coprime = True
for i in range(2, min(a, b) + 1):
if a % i == 0 and b % i == 0:
is_coprime = False
break
return is_coprime
assert coprime_alternate(4, 9)
assert not coprime_alternate(3, 6)
Things to Remember
• Python具有循环后else块的特殊语法
• else块会在循环没有break时执行。
• 避免使用这种不直观、令人困惑的语法。可以用辅助函数、结果变量等方法替代
文章转载自一只大鸽子,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




