跳转到内容

Python 3 非程序员教程/数到 10

来自维基教科书,开放的书籍,开放的世界

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

Fibonacci-method3.py

a = 0
b = 1
count = 0
maxcount = 20

#once loop is started we stay in it
while count < maxcount:
    count += 1
    olda = a
    a = a + b
    b = olda
    print(olda,end=" ")
print()

输出

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

编写一个程序,提示用户输入登录名和密码。然后,当他们输入“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,我们还没有介绍它。你可能已经猜到它是如何工作的了。


Python 3 非程序员教程
 ← 谁在那里? 数到 10 决策 → 
华夏公益教科书