Python 3 非程式設計師教程/數到 10
介紹我們的第一個控制結構。通常情況下,計算機從第一行開始,然後向下執行。控制結構改變語句執行的順序,或決定是否執行某個語句。以下是一個使用 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,我們還沒有介紹它。你可能已經猜到它是如何工作的了。