《Python程式設計:從入門到實踐》筆記。
本章主要介紹如何進行使用者輸入,while
迴圈,以及與迴圈配合使用的break
,continue
語句。
1. input() 函式
在Python中,使用input()
函式獲取使用者輸入,這裡請注意:input()
的返回值為字串。如果輸入的是數字,並且要用於後續計算,需要進行型別轉換。input()
函式可以傳入字串引數作為輸入提示,如下:
# 程式碼:
number = input()
# 判斷資料型別的兩種方法
print(type(number))
print(isinstance(number, str))
print(int(number) ** 2) # int()函式將字串轉換成整數
# 如果提示超過一行,可以將提示放在變數中,再將變數傳入input();
# 並且最好在提示後面留一個空格以區分提示和使用者輸入
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
# 結果:
123
<class `str`>
True
15129
Tell me something, and I will repeat it back to you: Hello, everyone!
Hello, everyone!
判斷奇偶(作為對前文常見運算的補充):取模運算%
,返回餘數
# 程式碼:
number = input("Enter a number, and I`ll tell you if it`s even or odd: ")
number = int(number)
if number % 2:
print("
The number " + str(number) + " is even.")
else:
print("
The number " + str(number) + " is odd.")
# 結果:
Enter a number, and I`ll tell you if it`s even or odd: 123
The number 123 is even.
2. while 迴圈簡介
for
迴圈用於針對集合中的每個元素的一個程式碼塊,而while
迴圈不斷地執行,直到指定的條件不滿足為止。比如,讓使用者選擇何時退出:
# 程式碼:
prompt = "
Tell me something, and I will repeat it back to you:"
prompt += "
Enter `quit` to end the program. "
message = ""
while message != "quit":
message = input(prompt)
if message != "quit":
print(message)
# 結果:
Tell me something, and I will repeat it back to you:
Enter `quit` to end the program. Hello everyone!
Hello everyone!
Tell me something, and I will repeat it back to you:
Enter `quit` to end the program. Hello again.
Hello again.
Tell me something, and I will repeat it back to you:
Enter `quit` to end the program. quit
2.1 使用標誌
在上述程式碼中我們直接對輸入資料進行判斷,這樣做在簡單的程式中可行,但複雜的程式中,如果有多個狀態同時決定while
迴圈的繼續與否,要是還用上述的方法,則while
迴圈的條件判斷將很長很複雜,這時可以定義一個變數作為標誌來代替多個條件。使用標誌來改寫上述程式碼:
prompt = "
Tell me something, and I will repeat it back to you:"
prompt += "
Enter `quit` to end the program. "
active = True
while active:
message = input(prompt)
if message != "quit":
active = False
else:
print(message)
在複雜的程式中,如很多事件都會導致程式停止執行的遊戲中,標誌很有用:在其中的任何一個事件導致活動標誌變為False
時,主遊戲迴圈將退出。
2.2 使用break退出迴圈
要立即退出while
或者for
迴圈,不在執行迴圈中餘下的程式碼,也不管條件測試的結果如何,可使用break
語句。再將上述使用標誌的程式碼改寫為break:
prompt = "
Tell me something, and I will repeat it back to you:"
prompt += "
Enter `quit` to end the program. "
while True:
message = input(prompt)
if message != "quit":
break
print(message)
2.3 在迴圈中使用continue
如果滿足某條件時要返回迴圈開始處,而不是跳出迴圈,則使用continue
語句。以下是列印1到10中的所有奇數的程式碼:
# 程式碼:
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue
print(count)
# 結果:
1
3
5
7
9
break與continue的區別:break
跳過迴圈體內餘下的所有程式碼,並跳出迴圈;continue
跳過迴圈體內餘下的所有程式碼,回到迴圈體開始處繼續執行,而不是跳出迴圈體。
值得提醒的是,編寫迴圈時應避免死迴圈,或者叫做無限迴圈,比如while
迴圈忘記了變數自增。
3. 使用while迴圈來處理列表和字典
3.1 在列表之間移動元素
將未驗證使用者經驗證後變為已驗證使用者:
# 程式碼:
unconfirmed_users = ["alice", "brian", "candace"]
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
print("
The following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
# 結果:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
3.2 刪除包含特定值的所有列表元素
之前的章節中使用remove()
函式來刪除列表中的值,但只刪除了列表中的第一個指定值,以下程式碼迴圈刪除列表中指定的值:
# 程式碼:
pets = ["dog", "cat", "dog", "goldfish", "cat", "rabbit", "cat"]
print(pets)
while "cat" in pets:
pets.remove("cat")
print(pets)
# 結果:
[`dog`, `cat`, `dog`, `goldfish`, `cat`, `rabbit`, `cat`]
[`dog`, `dog`, `goldfish`, `rabbit`]
3.3 使用使用者輸入來填充字典
# 程式碼:
responses = {}
# 設定一個標誌,指出調查是否繼續
polling_active = True
while polling_active:
# 提示輸入被調查者的名字和回答
name = input("
What is your name? ")
response = input("Which mountain would you like to climb someday? ")
# 將回答存入字典
responses[name] = response
# 是否還有人要參與調查
repeat = input("World you like to let another person respond?(yes/ no) ")
if repeat == "no":
polling_active = False
# 調查結束,輸出結果
print("
--- Poll Results ---")
for name, response in responses.items():
print(name + " world like to climb " + response + ".")
# 結果:
What is your name? Eric
Which mountain would you like to climb someday? Denali
World you like to let another person respond?(yes/ no) yes
What is your name? Lynn
Which mountain would you like to climb someday? Devil`s Thumb
World you like to let another person respond?(yes/ no) no
--- Poll Results ---
Eric world like to climb Denali.
Lynn world like to climb Devil`s Thumb.
迎大家關注我的微信公眾號”程式碼港” & 個人網站 www.vpointer.net ~