1. 程式人生 > >廖雪峰網站:學習python基礎知識—循環(四)

廖雪峰網站:學習python基礎知識—循環(四)

con class strong 網站 python bre 計算 end hal

一、循環


1、for

names = [Michal, Bob, tracy]
for name in names:
    print(name)

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7,8,9,10]:
    sum = sum + x
    print(sum)

# 打印數字 0 - 9
for x in range(10):
    print(x)

2、while

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
    print
(sum) n = 1 while n <= 100: if n > 10: # 當n = 11時,條件滿足,執行break語句 break # break語句會結束當前循環 print(n) n = n + 1 print("end") n = 0 while n < 10: n = n + 1 if n % 2 == 0: # 如果n是偶數,執行continue語句 continue # continue語句會直接繼續下一輪循環,後續的print()語句不會執行
print(n) # 計算1+2+3+...+100: sum = 0 n = 1 while n <= 100: sum = sum + n n = n + 1 print(sum) # 計算1x2x3x...x100: acc = 1 n = 1 while n <= 100: acc = acc * n n = n + 1 print(acc)

廖雪峰網站:學習python基礎知識—循環(四)