1. 程式人生 > >python學習筆記4(while語句)

python學習筆記4(while語句)

while語句

格式
while 表示式:
語句

邏輯:當程式執行到while語句時,首先計算表示式的值,如果表達是的值為假,那麼結束整個while語句,如果表示式的值為真,則執行語句,執行完語句再去計算表示式的值。如果表示式的值為假,那麼結束整個while語句,如果表示式的值為真,則執行語句,執行完語句再去計算表示式的值,如此迴圈往復,知道表示式的值為假時停止。
示例:

#列印從1到5,5個數
num = 1
while num <= 5
    print(num)
    num += 1

#計算1+2+3+……+100
num = 1
sum = 0
while num <= 100:
    sum += num
    num += num
print('sum = %d' %(sum))

#輸出一個字串中的所有字元
str = "sunck is a handsome man"
index = 0
while index <  len(str):   #  index < 19
    print("str[%d] = %s" % (index, str[index]))
    index += 1
#輸出:
str[0] = s
str[1] = u
str[2] = n
str[3] = c
str[4] = k
str[5] =  
str[6] = i
str[7] = s
str[8] =  
str[9] = a
str[10] =  
str[11] = h
str[12] = a
str[13] = n
str[14] = d