在Python的学习过程中,for…else…, while…else…语法可能是比较令人困惑的一个Python知识点。先来看一段Python官方的说明:
“Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.”
Python循环语句(for, while)有可能带一个else分支,当一个for循环正常执行完毕时或者当一个while循环正常执行完毕(循环条件变为false)时它被触发执行,但是如果这个循环被break语句非正常中止时,则这个else分支不执行。让我们来看几个例子:
1)for循环正常执行:
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> for i in range(7): ... print(i) ... else: ... print("No abnormal interruption") ... 0 1 2 3 4 5 6 No abnormal interruption |
2) for循环“非正常”break中断:
1 2 3 4 5 6 7 8 9 10 11 | >>> for i in range(7): ... print(i) ... if i == 3: ... break ... else: ... print("No abnormal interruption") ... 0 1 2 3 |
3) while循环正常执行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> i = 0 >>> while i < 7: ... print(i) ... i += 1 ... else: ... print("No abnormal interruption") ... 0 1 2 3 4 5 6 No abnormal interruption |
4) while循环“非正常”break中断:
1 2 3 4 5 6 7 8 9 10 11 12 | >>> i = 0 >>> while i < 7: ... print(i) ... i += 1 ... if i == 3: ... break ... else: ... print("No abnormal interruption") ... 0 1 2 |
总结起来就是:当循环中没有break时,else被执行,当循环中有break并且被触发时,else不被执行,类似这个case,即使循环语句中有break,但是如果没有触发break正常执行完毕,也会执行else:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> for i in range(7): ... print(i) ... if i > 7: ... break ... else: ... print("No abnormal interruption") ... 0 1 2 3 4 5 6 No abnormal interruption |
那么,这个有点绕口的Python语法糖有什么好处呢?让我们再看一个Case,这个Case参考自Python官方的一个寻找素数的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | >>> for n in range(2, 20): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 10 equals 2 * 5 11 is a prime number 12 equals 2 * 6 13 is a prime number 14 equals 2 * 7 15 equals 3 * 5 16 equals 2 * 8 17 is a prime number 18 equals 2 * 9 19 is a prime number |
想一想,如果没有else语句,如何实现?我是这样实现的,加一个flag标志来判断:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | >>> for n in range(2, 20): ... flag = 0 ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... flag = 1 ... break ... if flag == 0: ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 10 equals 2 * 5 11 is a prime number 12 equals 2 * 6 13 is a prime number 14 equals 2 * 7 15 equals 3 * 5 16 equals 2 * 8 17 is a prime number 18 equals 2 * 9 19 is a prime number |
这样看来,是不是觉得前者更 pythonic 一些?
注:原创文章,转载请注明出处及保留链接“Python时代”:https://www.pythonage.com/
本文链接地址:Python Tip 1:Python循环语句中的else语法(for else, while else)