Python 基礎(三)——流程控制之break 、continue 、else
阿新 • • 發佈:2018-01-01
sim 流程 tin rime con python 基礎 完整 .py gpo if 語句。)
break
break 語句和 C 中的類似,用於跳出最近的一級 for 或 while 循環。
循環可以有一個 else
子句;它在循環叠代完整個列表(對於 for )或執行條件為 false (對於 while )時執行,但循環被 break 中止的情況下不會執行。以下搜索素數的示例程序演示了這個子句:
>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, ‘equals‘, x, ‘*‘, n//x) ...break ... else: ... # loop fell through without finding a factor ... 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
(Yes, 這是正確的代碼。看仔細:else
語句是屬於 for 循環之中, 不是
continue
continue 語句是從 C 中借鑒來的,它表示循環繼續執行下一次叠代:
>>> for num in range(2, 10): ... if num % 2 == 0: ... print("Found an even number", num) ... continue ... print("Found a number", num) Found an even number 2 Found a number 3 Found an even number 4 Found a number5 Found an even number 6 Found a number 7 Found an even number 8 Found a number 9
Python 基礎(三)——流程控制之break 、continue 、else