跳转到内容

使用 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 循环

[编辑 | 编辑源代码]

通常情况下,计算机从第一行开始,然后向下执行。控制结构改变语句的执行顺序或决定是否执行某个语句。以下是一个使用 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 具有一个小的蜂鸣器,可以一次播放一个音符。我们可以控制 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.


使用 Linkbot 学习 Python 3
 ← 这里是谁? 计数到 10 决策 → 
华夏公益教科书