Published 9月 11, 2018 by with 0 comment

習題33 - while循環




這次是學while語句.
While 跟 if 類似, 但while下面的程式碼會不止執行一次,
而是執行完後再跳回while的頂部再執行一次,
直到程式的布林表達式為假.

用Notepad++打下列的程式碼,
另存為ex33.py. 我附上中文注釋方便好讀.
# 先設定i值為0, 再設定一個numbers空列表.
i = 0
numbers = []

while i < 6:
    # 第一次執行時, i = 0
    print(f"At the top i is {i}")
    # 然後把0用append 加入numbers列表,
    # 必要時, 可在這加入下面這一行,
    #print(">>> i = ", i, "and numbers list = ", numbers, "\n")
    # 來看此時的i與numbers值
    numbers.append(i)
    
    # 然後 i = 0 + 1 = 1
    i = i + 1
    # 第一次執行時, numbers列表內有個0
    print("Number now: ", numbers)
    # 第一次執行到這時 i = 1
    print(f"At the bottom i is {i}")

print ("The numbers: ")

# 執行6次後 (0 - 5), numbers列表內有[0, 1, 2, 3, 4, 5]
# 然後用for循環依次印出來
for num in numbers:
    print(num)

然後用Windows的cmd, 執行python.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW
C:\Users\Peter\Desktop\Python\LP3THW>python ex33.py
At the top i is 0
Number now:  [0]
At the bottom i is 1
At the top i is 1
Number now:  [0, 1]
At the bottom i is 2
At the top i is 2
Number now:  [0, 1, 2]
At the bottom i is 3
At the top i is 3
Number now:  [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Number now:  [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Number now:  [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5

C:\Users\Peter\Desktop\Python\LP3THW>

完成


最初發表 / 最後更新: 2018.09.11 / 2018.09.11

0 comments:

張貼留言