1、while循環
n=0 #初始條件
while n<=5: #判斷print('hello python') #要重復執行的代碼print(n) #注意同級代碼縮進相同n+=1 #計數器結果:
hello python
0
hello python
1
hello python
2
hello python
3
hello python
4
hello python
5
#求階乘和
sum=0
n=1
while n<=3:i=1ret=1while i<=n:ret*=ii+=1sum+=retn+=1
print(sum)結果:9
死循環:條件始終為真。
2、for循環
for i in range(3): #生成0~2一個序列print('hello')結果:
hello
hello
hello
#求階乘和
sum=0
ret=1
for n in range(4):ret=1for i in range(n+1):if i>0:ret=ret*isum=sum+ret
print(sum)結果:10