Published 9月 10, 2018 by with 0 comment

習題32 - 循環和列表



用Notepad++打下列的程式碼,
另存為ex32.py. 我附上中文注釋方便好讀.
# 設定列表(list), 注意!字符要用'號包起來.
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

# 用for 循環, 把列表內的東西由左到右分次提出來.
# this first kind of for-loop goes through a list
for number in the_count:
    print(f"This is count {number}")

# same as above
for fruit in fruits:
    print (f"A fruit of type: {fruit}")

# also we can go through mixed lists too
# notice we have to use {} since we don't know what's in it
for i in change:
    print(f"I got {i}")

# 我們也可以先建一個空列表.
# We can also build list, first start with an empty one
elements = []

# 然後用range, 依次把0-6放進列表.
# then use the range function to do 0 to 5 counts
for i in range (0, 6):
    print(f"Add {i} to the list.")
    # append是把新增的東西添加在列表的尾末.
    # append is a function that list understand
    elements.append(i)

# 最後用for把列表elements印出來.
# now we can print them out too
for i in elements:
    print(f"Element was {i}")

然後用Windows的cmd, 執行python.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW
C:\Users\Peter\Desktop\Python\LP3THW>python ex32.py
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got pennies
I got 2
I got dimes
I got 3
I got quarters
Add 0 to the list.
Add 1 to the list.
Add 2 to the list.
Add 3 to the list.
Add 4 to the list.
Add 5 to the list.
Element was 0
Element was 1
Element was 2
Element was 3
Element was 4
Element was 5

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

完成


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

0 comments:

張貼留言