Python_while回圈
1.語法
while 條件:
條件成立重復執行代碼1
條件成立重復執行代碼2
·······
# while 回圈語法
# 輸出5遍hello
i=1
while i<=5:
print('hello')
i+=1 #i=i+1
2計數器書寫習慣
# 計數器書寫習慣
# while 回圈語法
# 輸出5遍hello
i=0 #從0開始
while i<5: #小于5即可
print('hello')
i+=1 #i=i+1
3.回圈的應用
應用一:計算1-200的累加
# 計算1-200的累加
i=1
sum=0
while i<=200:
sum+=i
i+=1
print(sum)
應用二:計算1-200偶數累加和
# 計算1-200的偶數累加
# 方法一:
i=1
sum=0
while i<=200:
if i%2==0:
sum+=i
i+=1
print(sum)
# 方法二:
# i=0
i=2
sum=0
while i<=200:
sum+=i
i+=2
print(sum)
4.break與continue
(1)break:終止此回圈
(2)continue:退出當前一次回圈繼續執行下一次回圈代碼
# break陳述句
# 需求:一共5個蘋果,吃到第4個吃飽了
i=1
while i<=5:
if i==4:
print('吃飽了')
break
print(f'這是我吃的第{i}個蘋果')
i+=1

# continue陳述句
# 需求:一共5個蘋果,吃到第3個吃出了蟲子,但還想繼續吃
i=1
while i<=5:
if i==3:
print('吃出一個大蟲子,這個蘋果不吃了')
# 如果使用continue,在continue之前一定要修改計數器,否則進入死回圈
i+=1
continue
print(f'這是我吃的第{i}個蘋果')
i+=1

5.while回圈嵌套
(1)語法:
while 條件1:
條件1成立時執行的代碼
·······
while 條件2:
條件2成立時執行的代碼
··········
# while回圈嵌套
# 需求:三遍hello,一遍world,整體執行三次
j=0
while j<3:
i=0
while i<3:
print('hello')
i+=1
print('world')
print('---------')
j+=1

(2)實際應用
# 需求:9*9乘法表
j=1
while j<=9:
i=1 #一行開始
while i<=j:
print(f'{i}*{j}={i*j}',end='\t')
i+=1 #一行結束
print() #換行
j+=1

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/260006.html
標籤:其他
上一篇:云計算專業防火墻NAT實驗
下一篇:訊息佇列之-Kafka
