在學習python語言中發現python中跳出迴圈有兩種方法,分別是break和continue,但是兩種方法的區別一直不太清楚,也沒有找到乙個比較明確的說明,經過自己實際編碼對比,基本上掌握了用法。
首先,寫一段python的迴圈**,如下:
for fruit in foods:
if fruit == "banan":
print("no more banna please!")
print("great, delicious " + fruit)
else:
print("i am so glad: no banan!")
print("finally, i finished stuffing myself")
no more banna please!
great, delicious banan
great, delicious orange
great, delicious pear
i am so glad: no banan!
finally, i finished stuffing myself
for fruit in foods:
if fruit == "banan":
print("no more banna please!")
break
print("great, delicious " + fruit)
else:
print("i am so glad: no banan!")
print("finally, i finished stuffing myself")
no more banna please!
finally, i finished stuffing myself
for fruit in foods:
if fruit == "banan":
print("no more banna please!")
continue
print("great, delicious " + fruit)
else:
print("i am so glad: no banan!")
print("finally, i finished stuffing myself")
no more banna please!
great, delicious orange
great, delicious pear
i am so glad: no banan!
finally, i finished stuffing myself
python中break和continue的區別
break 應用在迴圈中,結束當前迴圈 continue 應用在迴圈中,結束當前正在執行的迴圈,繼續下一次迴圈 例項 統計100 200之間的質數的個數 質數 只能被1和它本身整除的數被稱為質數 假設法 假設任意乙個數是質數,然後尋找條件推翻假設 num 100count 0while num 20...
python中break 和continue的區別
break 只能在while,和for迴圈中 if不行 會報錯 break outside loop break跳出迴圈 1.打破的是最小封閉的while或for迴圈,在這裡我是這麼理解的,直接終止while迴圈,如果巢狀了多層for迴圈終止最內層迴圈.eg while true print 123...
python中的break語句
檔名稱 a.py 作 者 孔雲 問題描述 隨機產生色子的一面 數字1 6 給使用者三次猜測機會,程式給出猜測提示 偏大或偏下 如果猜測正確,則提示正確中斷迴圈 如果三次均猜錯,退出迴圈。問題分析 本程式中使用隨機函式產生隨機整數,設定迴圈初值為1,迴圈三次,在迴圈體中輸入猜測並進行判斷,若密碼正確則...