# 控制結構
## 判斷陳述句
基于一定的條件判斷是否要執行代碼
一般結構:
```jupyter
if <condition 1>:
<statement 1>
<statement 2>
elif <condition 2>:
<statements>
else:
<statements>
例如:
x = 0
if x > 0:
print "x is positive"
elif x == 0:
print "x is zero"
else:
print "x is negative"
elif 的個數沒有限制,可以是1個或者多個,也可以沒有,
else 最多只有1個,也可以沒有,
可以使用 and , or , not 等關鍵詞結合多個判斷條件:
回圈結構
將一段代碼重復執行多次,
while回圈結構:
while <condition>:
<statesments>
例如:
i = 0
total = 0
while i < 1000000:
total += i
i += 1
print total
for回圈結構:
for <variable> in <sequence>:
<indented block of code>
例如:
total = 0
for i in range(100000):
total += i
print total
中斷陳述句
continue陳述句:
遇到 continue 的時候,程式會回傳到回圈的最開始重新執行,
break陳述句:
遇到 break 的時候,程式會跳出回圈,不管回圈條件是不是滿足,
else陳述句
與 if 一樣, while 和 for 回圈后面也可以跟著 else 陳述句,不過要和break一起連用,
當回圈正常結束時,回圈條件不滿足, else 被執行;
當回圈被 break 結束時,回圈條件仍然滿足, else 不執行,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/553586.html
標籤:其他
下一篇:返回列表
