跳转到内容

使用 Linkbot/决策学习 Python 3

来自 Wikibooks,开放世界中的开放书籍

if 语句

[编辑 | 编辑源代码]

我一直认为我应该用热身打字练习来开始每一章,所以这里有一个简短的程序来计算整数的绝对值

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 部分。如果 ifelif 表达式都不为真,则执行 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 语句中进行多个测试。

移动 Linkbot 的电机

[编辑 | 编辑源代码]

在上一章 谁在那里? 中,我们看到可以使用 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 将同时移动其任何/所有电机。

command_linkbot.py

[编辑 | 编辑源代码]

在这个例子中,我们想创建一个程序,我们可以用它来移动我们的 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!')


使用 Linkbot 学习 Python 3
 ← 数到 10 决策 Linkbot 多任务 → 
华夏公益教科书