1. 程式人生 > >python迴圈學習

python迴圈學習

python中的for迴圈比Java中的更加簡練有點類似於Scala基本語法如下:

cities = ["beijing", "shanghai", "tianjin"]
for city in cities:
    print(city.title())

while迴圈基本一樣,基本語法如下:

i = 0
 while i < 9:
    print(i)
    i += 1

迴圈跳出包括關鍵字break,continue其中break直接結束跳出迴圈,continue跳過本次迭代進入下次迭代直至迴圈完成;

測試demo如下:

nums = rang(8)
for num in nums:
    if num % 2 == 0:
        print(num)
        break
for num in nums:
    if num % 2 ==0:
        print(num)
        continue

可以想一下輸出結果;