Python 005:循環語句

Python 005:循環語句

循環語句

1.while循環:用於功能循環;

----------------------------------------------------

count = 0

while count < 5:

print (count, " 小於 5")

count = count + 1

else:

print (count, " 大於或等於 5")

----------------------------------------------------

2.for循環:遍歷循環,用於迭代出list或tuple中的元素;

----------------------------------------------------

sites = ["Baidu", "Google","Runoob","Taobao"]

for site in sites:

----------------------------------------------------

m = [i**2 for i in range(5)]

# 運行結果:[0,1,4,9,16]

----------------------------------------------------

for i in range(0,10):

if i<3:

print(loop,i)

else:

continue

print(mm)

# 運行結果:

loop 0

mm

loop 1

mm

loop 2

mm

----------------------------------------------------

其他

1.range函數:遍歷序列函數[m,n)

----------------------------------------------------

a = [Google, Baidu, Runoob, Taobao, QQ]

for i in range(len(a)):

print(i, a[i])

----------------------------------------------------

r =range(0,8,1) # 0是起始位置,8是末位位置(注意不包含),1是間隔數量;

#運行結果:[0,1,2,3,4,5,6,7] # 返回的是列表;

----------------------------------------------------

break、continue、pass

break:該條件下,不執行後面的循環;

continue:特定條件下不執行部分程序;

pass:特定條件下才執行部分程序;

2.break語句:跳出整個循環;

----------------------------------------------------

a = [Google, Baidu, Runoob, Taobao, QQ]

for letter in Runoob:

if letter == o:

break

print (當前字母為 :, letter)

----------------------------------------------------

3.continue語句:跳出本次循環,進入下一次循環;# 即停止後面的循環,開始下一次循環

----------------------------------------------------

a = [Google, Baidu, Runoob, Taobao, QQ]

for letter in Runoob:

if letter == o:

continue

print (當前字母 :, letter)

----------------------------------------------------

2.pass語句:佔位符作用,只有符合要求的情況才會執行後面的內容;

----------------------------------------------------

a = [Google, Baidu, Runoob, Taobao, QQ]

for i in a:

if i == o:

pass

print(pass是佔位符作用)

print(i)

----------------------------------------------------

推薦閱讀:

AppleScript類自然語言與非英語語法設計
如何編寫優質的API文檔?
如何學好HTML5?學Web前端需不需要基礎?
大數據時代對編程有什麼影響?
測試的道理

TAG:編程 | 編程語言 |