Python學習之路6-用戶輸入和while循環

《Python編程:從入門到實踐》筆記。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!
複製代碼

判斷奇偶(做爲對前文常見運算的補充):取模運算%,返回餘數app

# 代碼:
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)

if number % 2:
    print("\nThe number " + str(number) + " is even.")
else:
    print("\nThe 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 = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter '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 = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter '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:ui

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

while True:
    message = input(prompt)
    if message != "quit":
        break
    print(message)
複製代碼

2.3 在循環中使用continue

若是知足某條件時要返回循環開始處,而不是跳出循環,則使用continue語句。如下是打印1到10中的全部奇數的代碼:spa

# 代碼:
count = 0
while count < 10:
    count += 1
    if count % 2 == 0:
        continue
    print(count)

# 結果:
1
3
5
7
9
複製代碼

break與continue的區別break跳過循環體內餘下的全部代碼,並跳出循環;continue跳過循環體內餘下的全部代碼,回到循環體開始處繼續執行,而不是跳出循環體。 值得提醒的是,編寫循環時應避免死循環,或者叫作無限循環,好比while循環忘記了變量自增。.net

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("\nThe 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("\nWhat 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("\n--- 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 ~

相關文章
相關標籤/搜索