跳轉到內容

使用Linkbot學習Python 3/For迴圈

來自Wikibooks,開放世界中的開放書籍

這是本章的新打字練習

onetoten = range(1, 11)
for count in onetoten:
    print(count)

以及始終存在的輸出

1
2
3
4
5
6
7
8
9
10

輸出看起來非常熟悉,但程式程式碼看起來有所不同。第一行使用range函式。range函式使用兩個引數,例如range(start, finish)start是生成的第一個數字。finish比最後一個數字大1。請注意,此程式可以用更短的方式完成

for count in range(1, 11):
    print(count)

range函式返回一個可迭代物件。這可以使用list函式轉換為列表。以下是一些示例,說明range命令是如何工作的

>>> range(1, 10)
range(1, 10)
>>> list(range(1, 10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(-32, -20))
[-32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21]
>>> list(range(5,21))
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(21, 5))
[]

下一行for count in onetoten:使用for控制結構。for控制結構類似於for variable in list:list從列表的第一個元素開始,到最後一個元素結束。當for遍歷列表中的每個元素時,它會將每個元素放入variable中。這允許在每次執行for迴圈時使用variable。以下是一個演示的示例(您不必輸入此示例)

demolist = ['life', 42, 'the universe', 6, 'and', 7, 'everything']
for item in demolist:
    print("The current item is:",item)

輸出為

The current item is: life
The current item is: 42
The current item is: the universe
The current item is: 6
The current item is: and
The current item is: 7
The current item is: everything

請注意for迴圈是如何遍歷並將item設定為列表中每個元素的。那麼,for有什麼用呢?第一個用途是遍歷列表的所有元素,並對每個元素執行某些操作。以下是如何快速將所有元素加起來的方法

list = [2, 4, 6, 8]
sum = 0
for num in list:
    sum = sum + num

print("The sum is:", sum)

輸出僅僅是

總和為:20

或者您可以編寫一個程式來查詢列表中是否存在任何重複項,就像此程式所做的那樣

list = [4, 5, 7, 8, 9, 1, 0, 7, 10]
list.sort()
prev = None
for item in list:
    if prev == item:
        print("Duplicate of", prev, "found")
    prev = item

為了確保萬無一失

Duplicate of 7 found

好的,那麼它是如何工作的呢?這是一個特殊的除錯版本,可以幫助您理解(您不需要輸入此版本)

l = [4, 5, 7, 8, 9, 1, 0, 7, 10]
print("l = [4, 5, 7, 8, 9, 1, 0, 7, 10]", "\t\tl:", l)
l.sort()
print("l.sort()", "\t\tl:", l)
prev = l[0]
print("prev = l[0]", "\t\tprev:", prev)
del l[0]
print("del l[0]", "\t\tl:", l)
for item in l:
    if prev == item:
        print("Duplicate of", prev, "found")
    print("if prev == item:", "\t\tprev:", prev, "\titem:", item)
    prev = item
    print("prev = item", "\t\tprev:", prev, "\titem:", item)

輸出為

l = [4, 5, 7, 8, 9, 1, 0, 7, 10]        l: [4, 5, 7, 8, 9, 1, 0, 7, 10]
l.sort()                l: [0, 1, 4, 5, 7, 7, 8, 9, 10]
prev = l[0]             prev: 0
del l[0]                l: [1, 4, 5, 7, 7, 8, 9, 10]
if prev == item:        prev: 0         item: 1
prev = item             prev: 1         item: 1
if prev == item:        prev: 1         item: 4
prev = item             prev: 4         item: 4
if prev == item:        prev: 4         item: 5
prev = item             prev: 5         item: 5
if prev == item:        prev: 5         item: 7
prev = item             prev: 7         item: 7
Duplicate of 7 found
if prev == item:        prev: 7         item: 7
prev = item             prev: 7         item: 7
if prev == item:        prev: 7         item: 8
prev = item             prev: 8         item: 8
if prev == item:        prev: 8         item: 9
prev = item             prev: 9         item: 9
if prev == item:        prev: 9         item: 10
prev = item             prev: 10        item: 10

我在程式碼中添加了這麼多print語句的原因是為了讓您瞭解每一行的作用。(順便說一句,如果您無法弄清楚為什麼程式無法正常工作,請嘗試在您想要了解正在發生的事情的地方新增許多print語句。)首先,程式從一個無聊的舊列表開始。接下來,程式對列表進行排序。這樣可以將任何重複項放在一起。然後程式初始化一個prev(ious)變數。接下來,刪除列表的第一個元素,以便不會錯誤地認為第一個專案是重複項。接下來,進入for迴圈。檢查列表的每個專案是否與前一個專案相同。如果是,則找到重複項。然後更改prev的值,以便下次執行for迴圈時,prev是當前專案的先前專案。果然,發現7是重複項。(請注意如何使用\t打印製表符。)

使用for迴圈的另一種方法是執行某些操作一定的次數。以下是一些程式碼,用於打印出斐波那契數列的前9個數字

a = 1
b = 1
for c in range(1, 10):
    print(a, end=" ")
    n = a + b
    a = b
    b = n

輸出令人驚訝

1 1 2 3 5 8 13 21 34

使用for迴圈可以完成的所有操作也可以使用while迴圈完成,但是for迴圈提供了一種簡單的方法來遍歷列表中的所有元素或執行某些操作一定的次數。

Linkbot示例

[編輯 | 編輯原始碼]

在此示例中,Linkbot將在固定的次數內播放變化的音調,而持續時間保持不變。Linkbot還可以改變音調和持續時間固定的次數。在這裡,我們使用一個在固定值範圍內執行的for迴圈。

setBuzzerFrequency.py

import barobo
dongle = barobo.Dongle()
dongle.connect()
robot = dongle.getLinkbot('6wbn') # Replace '6wbn' with the serial ID on your Linkbot
import time     # For time.sleep()
t=1             # Set a value to be used for the duration of the note
for i in range (33,43):         # Select which keys on a piano keyboard to use for the tones
    k=pow(2,(i-49)/12)*440      # Determines the frequency of the note to be played
    robot.setBuzzerFrequency(k) # Directs the Linkbot to play this frequency   
    time.sleep(t)               # Pauses the program while the note is played

robot.setBuzzerFrequency(0)     # Turns off the piezo speaker at the end of the program

執行此示例時,嘗試更改迴圈範圍和時間值以建立有趣的音效。

使用Linkbot學習Python 3
 ← 列表 For迴圈 布林表示式 → 
華夏公益教科書