使用 Linkbot/決策學習 Python 3
我一直認為我應該用熱身打字練習來開始每一章,所以這裡有一個簡短的程式來計算整數的絕對值
n = int(input("Number? "))
if n < 0:
print("The absolute value of", n, "is", -n)
else:
print("The absolute value of", n, "is", n)
這是我執行此程式兩次的輸出
Number? -34 The absolute value of -34 is 34
Number? 1 The absolute value of 1 is 1
那麼當計算機看到這段程式碼時它會做什麼呢?首先,它使用語句 "n = int(input("Number? "))" 提示使用者輸入一個數字。接下來,它讀取行 "if n < 0:"。如果 n 小於零,Python 執行行 "print("The absolute value of", n, "is", -n)"。否則,它執行行 "print("The absolute value of", n, "is", n)"。
更正式地說,Python 會檢視表示式 n < 0 是真還是假。一個 if 語句後面跟著一個縮排的塊語句,當表示式為真時會執行這些語句。可選地在 if 語句之後是一個 else 語句和另一個縮排的塊語句。如果表示式為假,則執行第二個塊語句。
表示式可以有許多不同的測試。以下是一張所有測試的表格
| 運算子 | 函式 |
|---|---|
<
|
小於 |
<=
|
小於或等於 |
>
|
大於 |
>=
|
大於或等於 |
==
|
等於 |
!=
|
不等於 |
if 命令的另一個特性是 elif 語句。它代表 else if,意思是如果原始 if 語句為假,但 elif 部分為真,則執行 elif 部分。如果 if 或 elif 表示式都不為真,則執行 else 塊中的內容。以下是一個示例
a = 0
while a < 10:
a = a + 1
if a > 5:
print(a, ">", 5)
elif a <= 3:
print(a, "<=", 3)
else:
print("Neither test was true")
以及輸出
1 <= 3 2 <= 3 3 <= 3 Neither test was true Neither test was true 6 > 5 7 > 5 8 > 5 9 > 5 10 > 5
注意 elif a <= 3 只有在 if 語句不為真時才會被測試。可以有多個 elif 表示式,允許在單個 if 語句中進行多個測試。
在上一章 誰在那裡? 中,我們看到可以使用 moveJoint() 函式移動 Linkbot 的電機。它通常像這樣使用
myLinkbot.moveJoint(1, 180)
其中第一個引數是要移動的電機,第二個引數是要移動的角度(以度為單位)。上面的程式碼將以正方向將電機 "1" 移動 180 度。
如果你想一次移動多個電機怎麼辦?Linkbot 還具有一個 move() 函式,它可以做到這一點。它看起來像這樣
myLinkbot.move(90, 180, 270)
move() 函式希望在括號內包含三個數字。第一個數字是移動電機 1 的角度,第二個數字是移動電機 2 的角度,第三個數字是移動電機 3 的角度。如果你的 Linkbot 只有兩個電機,則沒有電機的面的值會被忽略。例如,如果我有一個 Linkbot-I 並運行了上面的示例程式碼,則 "180" 會被忽略,因為電機 2 不是可移動電機。相反,Linkbot 會將電機 1 向前移動 90 度,並將電機 3 向前移動 270 度。
當 move() 函式執行時,Linkbot 將同時移動其任何/所有電機。
在這個例子中,我們想建立一個程式,我們可以用它來移動我們的 Linkbot。這個演示將使用 python break 命令。在上一章中,我們看到 Python 會陷入“無限迴圈”。break 命令可以用於退出迴圈,即使迴圈條件仍然為真。
讓我們先從讓 Linkbot 向前和向後移動開始。要執行這個演示,你需要一個 Linkbot-I 和兩個輪子。也建議使用一個萬向輪,但不是必需的。
import barobo
dongle = barobo.Dongle()
dongle.connect()
myLinkbot = dongle.getLinkbot('abcd') # Replace abcd with your Linkbot's serial ID
while True: # This is an infinite loop. Get out by using the "break" statement
command = input('Please enter a robot command or "quit" to exit the program: ')
if command == 'forward':
# Rotate the wheels 180 degrees to move the robot forward
myLinkbot.move(180, 0, -180) # Motor 3 has to spin in the negative direction to move the robot forward
elif command == 'backward':
myLinkbot.move(-180, 0, 180)
elif command == 'quit':
break
else:
print('I\'m sorry. I don\'t understand that command.')
print('Goodbye!')
關於字串的說明
你可能已經注意到,在程式的最後,有一行程式碼是 print('I\'m sorry. I don\'t understand that command.'),程式碼中有一些奇怪的反斜槓。但是,當你執行程式時,它不會列印這些反斜槓。這些反斜槓實際上起著重要的作用。
當 Python 遇到單引號 ' 或雙引號 " 時,它知道接下來將是一個以相同型別的引號結尾的字串,該引號是它開始的引號。但是,如果我們想將一些引號包含在字串中呢?請考慮以下程式碼
mystring = "Hello there. My dog says "woof!" when he's bored."
當 Python 在 "Hello th... 中看到第一個引號時,它會說:“好的,這將是一個字串,一旦我看到另一個引號,這就是字串的結尾”。很快,Python 在 ...says "woof! 中看到了另一個引號,並認為“我找到了字串的結尾!”,但這不是我們字串的結尾!我們希望 Python 一直走到 ...bored." 處的結尾。我們如何告訴 Python "woof!" 周圍的引號是特殊的,並且我們的字串實際上並沒有在那裡結束呢?
答案是反斜槓。如果在引號前面有一個反斜槓,那麼對 Python 來說這是一個特殊指示,指示將該引號包含在字串中,而不是終止字串。因此,修正後的程式碼應該是
mystring = "Hello there. My dog says \"woof!\" when he's bored."
在這個例子中,he's 中的單引號會自動包含在字串中,因為字串以雙引號開頭,因此 Python 正在尋找一個雙引號來終止字串。
示例執行
Please enter a robot command or 'quit' to exit the program: forward Please enter a robot command or 'quit' to exit the program: backward Please enter a robot command or 'quit' to exit the program: aoeu I'm sorry. I don't understand that command. Please enter a robot command or 'quit' to exit the program: quit Goodbye!
equality.py
# This Program Demonstrates the use of the == operator
# using numbers
print(5 == 6)
# Using variables
x = 5
y = 8
print(x == y)
以及輸出
False False
high_low.py
# Plays the guessing game higher or lower
# This should actually be something that is semi random like the
# last digits of the time or something else, but that will have to
# wait till a later chapter. (Extra Credit, modify it to be random
# after the Modules chapter)
number = 7
guess = -1
print("Guess the number!")
while guess != number:
guess = int(input("Is it... "))
if guess == number:
print("Hooray! You guessed it right!")
elif guess < number:
print("It's bigger...")
elif guess > number:
print("It's not so big.")
示例執行
Guess the number! Is it... 2 It's bigger... Is it... 5 It's bigger... Is it... 10 It's not so big. Is it... 7 Hooray! You guessed it right!
even.py
# Asks for a number.
# Prints if it is even or odd
number = float(input("Tell me a number: "))
if number % 2 == 0:
print(int(number), "is even.")
elif number % 2 == 1:
print(int(number), "is odd.")
else:
print(number, "is very strange.")
示例執行
Tell me a number: 3 3 is odd.
Tell me a number: 2 2 is even.
Tell me a number: 3.4895 3.4895 is very strange.
average1.py
# keeps asking for numbers until 0 is entered.
# Prints the average value.
count = 0
sum = 0.0
number = 1 # set to something that will not exit the while loop immediately.
print("Enter 0 to exit the loop")
while number != 0:
number = float(input("Enter a number: "))
if number != 0:
count = count + 1
sum = sum + number
if number == 0:
print("The average was:", sum / count)
示例執行
Enter 0 to exit the loop Enter a number: 3 Enter a number: 5 Enter a number: 0 The average was: 4.0
Enter 0 to exit the loop Enter a number: 1 Enter a number: 4 Enter a number: 3 Enter a number: 0 The average was: 2.66666666667
average2.py
# keeps asking for numbers until count numbers have been entered.
# Prints the average value.
#Notice that we use an integer to keep track of how many numbers,
# but floating point numbers for the input of each number
sum = 0.0
print("This program will take several numbers then average them")
count = int(input("How many numbers would you like to average: "))
current_count = 0
while current_count < count:
current_count = current_count + 1
print("Number", current_count)
number = float(input("Enter a number: "))
sum = sum + number
print("The average was:", sum / count)
示例執行
This program will take several numbers then average them How many numbers would you like to average: 2 Number 1 Enter a number: 3 Number 2 Enter a number: 5 The average was: 4.0
This program will take several numbers then average them How many numbers would you like to average: 3 Number 1 Enter a number: 1 Number 2 Enter a number: 4 Number 3 Enter a number: 3 The average was: 2.66666666667
編寫一個程式,該程式詢問使用者他們的姓名,如果他們輸入你的姓名,則說“這是一個好名字”,如果他們輸入“John Cleese”或“Michael Palin”,則告訴他們你對他們的感受;),否則告訴他們“你有一個好名字”。
name = input('Your name: ')
if name == 'Ada':
print('That is a nice name.')
elif name == 'John Cleese':
print('... some funny text.')
elif name == 'Michael Palin':
print('... some funny text.')
else:
print('You have a nice name.')
修改本節中高或低的程式,以跟蹤使用者輸入錯誤數字的次數。如果超過 3 次,則在最後列印“那一定很複雜”,否則列印“幹得好!”。
number = 7
guess = -1
count = 0
print("Guess the number!")
while guess != number:
guess = int(input("Is it... "))
count = count + 1
if guess == number:
print("Hooray! You guessed it right!")
elif guess < number:
print("It's bigger...")
elif guess > number:
print("It's not so big.")
if count > 3:
print("That must have been complicated.")
else:
print("Good job!")
編寫一個程式,該程式要求提供兩個數字。如果這兩個數字的和大於 100,則列印“這是一個大數字”。
number1 = float(input('1st number: '))
number2 = float(input('2nd number: '))
if number1 + number2 > 100:
print('That is a big number.')
修改前面介紹的 Linkbot 程式,以包含命令“turnright”、“turnleft”和“beep”。使“turnright”命令使機器人向右轉,“turnleft”命令使機器人向左轉,“beep”命令使機器人蜂鳴器響一秒鐘。
import barobo
import time # So we can use time.sleep() later
dongle = barobo.Dongle()
dongle.connect()
myLinkbot = dongle.getLinkbot('abcd') # Replace abcd with your Linkbot's serial ID
while True: # This is an infinite loop. Get out by using the "break" statement
command = input('Please enter a robot command or "quit" to exit the program: ')
if command == 'forward':
# Rotate the wheels 180 degrees to move the robot forward
myLinkbot.move(180, 0, -180) # Motor 3 has to spin in the negative direction to move the robot forward
elif command == 'backward':
myLinkbot.move(-180, 0, 180)
elif command == 'turnright':
myLinkbot.move(180, 0, 180)
elif command == 'turnleft':
myLinkbot.move(-180, 0, -180)
elif command == 'beep':
myLinkbot.setBuzzerFrequency(440)
time.sleep(1)
myLinkbot.setBuzzerFrequency(0)
elif command == 'quit':
break
else:
print('I\'m sorry. I don\'t understand that command.')
print('Goodbye!')