使用 Linkbot 學習 Python 3 / 計數到 10
課程資訊
**To Be Added** Vocabulary: Necessary Materials and Resources: Computer Science Teachers Association Standards: 5.2.CPP.5: Implement problem solutions using a programming language, including: looping behavior, conditional statements, logic, expressions, variables, and functions. Common Core Math Content Standards: Common Core Math Practice Standards: Common Core English Language Arts Standards:
通常情況下,計算機從第一行開始,然後向下執行。控制結構改變語句的執行順序或決定是否執行某個語句。以下是一個使用 while 控制結構的程式的原始碼
a = 0 # FIRST, set the initial value of the variable a to 0(zero).
while a < 10: # While the value of the variable a is less than 10 do the following:
a = a + 1 # Increase the value of the variable a by 1, as in: a = a + 1!
print(a) # Print to screen what the present value of the variable a is.
# REPEAT! until the value of the variable a is equal to 9!? See note.
# NOTE:
# The value of the variable a will increase by 1
# with each repeat, or loop of the 'while statement BLOCK'.
# e.g. a = 1 then a = 2 then a = 3 etc. until a = 9 then...
# the code will finish adding 1 to a (now a = 10), printing the
# result, and then exiting the 'while statement BLOCK'.
# --
# While a < 10: |
# a = a + 1 |<--[ The while statement BLOCK ]
# print (a) |
# --
以下是極其令人興奮的輸出
1 2 3 4 5 6 7 8 9 10
(你以為把你的計算機變成一個五美元的計算器後,情況就不可能變得更糟了嗎?)
那麼這個程式做了什麼?首先,它看到 a = 0 這行程式碼,並將 a 設定為零。然後它看到 while a < 10:,因此計算機檢查 a < 10 是否為真。計算機第一次看到這個語句時,a 為零,所以它小於 10。換句話說,只要 a 小於十,計算機就會執行縮排的語句。這最終會使 a 等於十(透過不斷地給 a 加一),然後 while a < 10 就不再為真了。到達那個點後,程式將停止執行縮排的行。
請務必在 while 語句行的末尾新增一個冒號“:”!
以下是另一個使用 while 的例子
a = 1
s = 0
print('Enter Numbers to add to the sum.')
print('Enter 0 to quit.')
while a != 0:
print('Current Sum:', s)
a = float(input('Number? '))
s = s + a
print('Total Sum =', s)
Enter Numbers to add to the sum. Enter 0 to quit. Current Sum: 0 Number? 200 Current Sum: 200.0 Number? -15.25 Current Sum: 184.75 Number? -151.85 Current Sum: 32.9 Number? 10.00 Current Sum: 42.9 Number? 0 Total Sum = 42.9
請注意,print 'Total Sum =', s 只在最後執行。while 語句隻影響縮排的程式碼行。!= 表示不等於,所以 while a != 0: 表示只要 a 不為零,就執行其後的縮排語句。
請注意,a 是一個浮點數,並不是所有浮點數都能被精確地表示,因此對它們使用 != 有時可能無法正常工作。嘗試在互動模式下輸入 1.1。
現在我們有了 while 迴圈,就可以讓程式永遠執行。一個簡單的方法是編寫一個像這樣的程式
while 1 == 1:
print("Help, I'm stuck in a loop.")
“==” 運算子用於測試運算子兩側表示式的相等性,就像之前使用的 “<” 用於“小於”一樣(你將在下一章中獲得所有比較運算子的完整列表)。
這個程式將輸出 Help, I'm stuck in a loop. 直到宇宙熱寂或你停止它,因為 1 將永遠等於 1。停止它的方法是同時按下 Control(或 Ctrl)鍵和 C(字母)。這將殺死程式。(注意:有時你需要在按下 Control-C 後再按回車鍵。)在某些系統上,除了殺死程序之外,沒有任何方法可以阻止它,所以請避免使用它!
Fibonacci-method1.py
# This program calculates the Fibonacci sequence
a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
count = count + 1
print(a, end=" ") # Notice the magic end=" " in the print function arguments
# that keeps it from creating a new line.
old_a = a # we need to keep track of a since we change it.
a = b
b = old_a + b
print() # gets a new (empty) line.
輸出
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
請注意,由於 print 引數中添加了額外的引數 end=" ",輸出在單行上。
Fibonacci-method2.py
# Simplified and faster method to calculate the Fibonacci sequence
a = 0
b = 1
count = 0
max_count = 10
while count < max_count:
count = count + 1
print(a, b, end=" ") # Notice the magic end=" "
a = a + b
b = a + b
print() # gets a new (empty) line.
輸出
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Password.py
# Waits until a password has been entered. Use Control-C to break out without
# the password
#Note that this must not be the password so that the
# while loop runs at least once.
password = str()
# note that != means not equal
while password != "unicorn":
password = input("Password: ")
print("Welcome in")
示例執行
Password: auo Password: y22 Password: password Password: open sesame Password: unicorn Welcome in
Linkbot 具有一個小的蜂鳴器,可以一次播放一個音符。我們可以控制 Linkbot 上蜂鳴器的頻率來生成不同的音調。公式 顯示瞭如何計算鋼琴琴鍵的頻率。真正的鋼琴有 88 個琴鍵,但讓我們看看我們是否可以讓我們的機器人從第 34 個琴鍵一直演奏到第 73 個琴鍵。
在 Python 中,要計算一個數字的“次方”,我們可以使用 ** 運算子。例如, 可以使用 Python 中的 2**3 來計算。
import barobo
dongle = barobo.Dongle()
dongle.connect()
robotID = input('Enter Linkbot ID: ')
robot = dongle.getLinkbot(robotID)
import time # imports the Python "time" module because we want to use "time.sleep()" later.
key=34 # Set key=34 which is the 34th key on a piano keyboard.
while key < 74: # While the key number is less than 74.
robot.setBuzzerFrequency(2**((key-49)/12.0)*440) # Play the frequency to the corresponding note.
time.sleep(.25) # Play the note for 0.25 seconds.
robot.setBuzzerFrequency(0) # Turn off the note
key=key+1 # Increase the key number by 1. This is the end of the loop. At this point,
# Python will check to see if the condition in the "while" statement,
# "key < 74", is true. If it is still true, Python will go back to the
# beginning of the loop. If not, the program exits the loop.
編寫一個程式,要求使用者輸入登入名和密碼。然後,當他們輸入“lock”時,需要輸入他們的使用者名稱和密碼來解鎖程式。
編寫一個程式,要求使用者輸入登入名和密碼。然後,當他們輸入“lock”時,需要輸入他們的使用者名稱和密碼來解鎖程式。
name = input("What is your UserName: ")
password = input("What is your Password: ")
print("To lock your computer type lock.")
command = None
input1 = None
input2 = None
while command != "lock":
command = input("What is your command: ")
while input1 != name:
input1 = input("What is your username: ")
while input2 != password:
input2 = input("What is your password: ")
print("Welcome back to your system!")
如果你希望程式連續執行,只需在整個程式周圍新增一個 while 1 == 1: 迴圈。在程式碼頂部新增此迴圈時,你需要縮排程式的其餘部分,但不用擔心,你不需要手動對每一行進行縮排!只需選中你想要縮排的所有內容,然後單擊 python 視窗頂部的“格式”下的“縮排”。
另一種方法是
name = input('Set name: ')
password = input('Set password: ')
while 1 == 1:
nameguess=""
passwordguess=""
key=""
while (nameguess != name) or (passwordguess != password):
nameguess = input('Name? ')
passwordguess = input('Password? ')
print("Welcome,", name, ". Type lock to lock.")
while key != "lock":
key = input("")
請注意 while (nameguess != name) or (passwordguess != password) 中的 or,我們還沒有介紹它。你可能已經猜到它的工作原理了。
修改 Linkbot 蜂鳴器程式,使其演奏從第 34 個琴鍵到第 74 個琴鍵的鋼琴上每隔三個琴鍵的音調。
import barobo
dongle = barobo.Dongle()
dongle.connect()
robotID = input('Enter Linkbot ID: ')
robot = dongle.getLinkbot(robotID)
import time # imports the Python "time" module because we want to use "time.sleep()" later.
key=34 # Set key=34 which is the 34th key on a piano keyboard.
while key < 74: # While the key number is less than 74.
robot.setBuzzerFrequency(2**((key-49)/12.0)*440) # Play the frequency to the corresponding note.
time.sleep(.25) # Play the note for 0.25 seconds.
robot.setBuzzerFrequency(0) # Turn off the note
key=key+3 # Increase the key number by 3. This is the end of the loop. At this point,
# Python will check to see if the condition in the "while" statement,
# "key < 74", is true. If it is still true, Python will go back to the
# beginning of the loop. If not, the program exits the loop.