python循環結構

python循環結構

1.1 使用while

Python 中沒有 do…while 循環

while … else 在條件語句爲 false 時執行 else 的語句塊:

list = [1,2,3,4,5]
i = 0

while i < len(list):
    print(list[i])
    i += 1

1
2
3
4
5

# while可以使用else語句
list = [1,2,3,4,5]
i = 0
while i < len(list):
    print(list[i])
    i += 1
else :
    print('**** 程序執行結束 *****')

1
2
3
4
5
**** 程序執行結束 *****

1.2 使用for

for循環可以遍歷任何序列的項目,如一個列表或者一個字符串。

一般結構如下

for <variable> in <sequence>:
    <statements>
else:
    <statements>
# 遍歷數字, 可以使用range方法
for i in range(6):
    print(i)
# 第二個參數不可達,第三個參數爲步長不指定時,默認爲1
for i in range(2,6,2):
    print(i)

0
1
2
3
4
5
2
4

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章