3、Python邏輯控制

if語句

if語句的語法如下:

if 條件1:
    執行語句
elif 條件2:
    執行語句
...
else:
    執行語句

elifelse if的縮寫。
示例:

x = 6
if x < 0:
    print('負數')
elif x == 0:
    print('0')
else:
    print('正整數')

for循環

for循環可以遍歷任何序列,如list或者字符串。
其語法如下:

# 序列可以是list、元組、字符串、文件
for 變量名 in 序列:
   執行代碼

示例:

# 遍歷字符串中的字符
for letter in 'Python':
    print('字母: ', letter)

# 遍歷list,list是有序的,因此遍歷結果固定
color_list = ['black', 'blue', 'pink']
for color in color_list:
    print('顏色:', color)

# 遍歷集合,集合無序,因此遍歷的結果是隨機的
color_set = {'black', 'blue', 'pink'}
for color in color_set:
    print('顏色:', color)

# 通過索引遍歷內容
color_tuple = ('black', 'blue', 'pink')
for index in range(len(color_tuple)):
    print('索引:%d, 顏色:%s' % (index, color_tuple[index]))

while循環

while循環語法:

while 條件:
    執行代碼

示例:

count = 0
while count < 9:
    print('num = %d' % count)
    count = count + 1

range()函數

range()會生成一個等差鏈表,語法
range(start, end, scan)
參數說明:
start: 從start開始計數,默認是從0開始。如range(x)等價於range(0,x,1)
end計數:計數到end結束,但不包括end。如range(0,x)[0,1,2,..,x-1],沒有x
scan:等差的差距,默認爲1.
示例:

for i in range(6):
    print(i) # 輸出0 1 2 3 4 5
for i in range(6, 10):
    print(i) # 輸出6 7 8 9
for i in range(10, 20, 2):
    print(i) # 輸出10 12 14 16 18

break、continue、pass關鍵字

break可以終止循環
continue可以跳過當前循環中剩餘的語句,進入下一次循環
pass用於保持程序結構的完整性.
示例:

for i in range(6):
    if i % 2 != 0:
        continue
    print('num = %d' % i)  # 輸出0 2 4

for s in 'let us go':
    if s == ' ':
        break
    print('string = %s' % s) # 輸出 l e t
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章