Python3 基础学习笔记 C06【用户输入和 while 循环】
CSDN 課程推薦:《8小時Python零基礎(chǔ)輕松入門》,講師齊偉,蘇州研途教育科技有限公司CTO,蘇州大學(xué)應(yīng)用統(tǒng)計專業(yè)碩士生指導(dǎo)委員會委員;已出版《跟老齊學(xué)Python:輕松入門》《跟老齊學(xué)Python:Django實(shí)戰(zhàn)》、《跟老齊學(xué)Python:數(shù)據(jù)分析》和《Python大學(xué)實(shí)用教程》暢銷圖書。
Python3 基礎(chǔ)學(xué)習(xí)筆記第六章【用戶輸入和 while 循環(huán)】
目錄
- 【6.1】函數(shù) input() 的工作原理
- 【6.1.1】使用 int() 來獲取數(shù)值輸入
- 【6.1.2】求模運(yùn)算符
- 【6.1.3】在 Python 2.7 中獲取輸入
- 【6.2】while 循環(huán)
- 【6.2.1】使用 while 循環(huán)
- 【6.2.2】讓用戶選擇退出循環(huán)
- 【6.2.3】使用標(biāo)志
- 【6.2.4】使用 break 退出循環(huán)
- 【6.2.5】在循環(huán)中使用 continue
- 【6.3】使用 while 循環(huán)來處理列表和字典
- 【6.3.1】在列表之間移動元素
- 【6.3.2】刪除包含特定值的所有列表元素
- 【6.3.3】使用用戶輸入來填充字典
【6.1】函數(shù) input() 的工作原理
函數(shù) input() 讓程序暫停運(yùn)行,等待用戶輸入一些文本。獲取用戶輸入后,Python將其儲存在一個變量當(dāng)中,以方便你使用;函數(shù) input() 返回為 string 類型
message = input("Please tell me your name:") print("Hello , " + message + "!")輸出結(jié)果如下:
Please tell me your name:anliy Hello , anliy!進(jìn)階:
message = "Please tell me your name so that we can personalize the messages you see." message += "\nWhat's your first name?" name = input(message) print("\nHello , " + name + "!")輸出結(jié)果如下:
Please tell me your name so that we can personalize the messages you see. What's your first name?trhxHello , trhx!【6.1.1】使用 int() 來獲取數(shù)值輸入
使用函數(shù) input() 時,Python會將用戶輸入解讀為字符串:
>>> age = input("How old are you?") How old are you?19 >>> age '19'為了解決這個問題,可以使用函數(shù) int() ,它讓Python將輸入視為數(shù)值:
>>> age = input("How old are you?") How old are you?19 >>> age = int(age) >>> age 19實(shí)例:
age = input("Please tell me your age:") age = int(age) if age >= 18:print("You are old enough to go to the Internet bar!") else:print("You are not old enough to go to Internet bar!")輸出結(jié)果如下:
Please tell me your age:17 You are not old enough to go to Internet bar!【6.1.2】求模運(yùn)算符
處理數(shù)值信息時,求模運(yùn)算符(%)是一個很有用的工具,它將兩個數(shù)相除并返回余數(shù):
>>> 4 % 3 1 >>> 5 % 3 2 >>> 8 % 2 0 >>> 7 % 3 1【6.1.3】在 Python 2.7 中獲取輸入
如果使用 Python 2.7,應(yīng)該使用函數(shù) raw_input() 來提示用戶輸入,這個函數(shù)與 Python 3 中的 input() 一樣,也將輸入解讀為字符串;Python 2.7 也包含函數(shù) input(),但它將用戶輸入解讀為Python代碼,并嘗試運(yùn)行它們
【6.2】while 循環(huán)
for 循環(huán)用于針對集合中的每一個元素的一個代碼塊,而 while 循環(huán)不斷地運(yùn)行,直到指定的條件不滿足為止
【6.2.1】使用 while 循環(huán)
一個簡單的 while 循環(huán):
num = 1 while num < 5:print(num)num += 1輸出結(jié)果如下:
1 2 3 4【6.2.2】讓用戶選擇退出循環(huán)
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)print(message)運(yùn)行程序:
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 quit【6.2.3】使用標(biāo)志
在要求很多條件都滿足才繼續(xù)運(yùn)行的程序中,可以定義一個變量,用于判斷整個程序是否處于活動狀態(tài),這個變量稱為標(biāo)志
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 = Falseelse:print(message)運(yùn)行結(jié)果與6.2.2一致
【6.2.4】使用 break 退出循環(huán)
要立即退出 while 循環(huán),不再運(yùn)行循環(huán)中余下的代碼,也不管條件測試的結(jié)果如何,可使用 break 語句,break 語句用于控制程序流程,可使用它來控制哪些代碼將執(zhí)行,哪些代碼不執(zhí)行
prompt = "\nPlease enter the name of a city you have visited:" prompt += "\nEnter 'quit' when you are finished." active = True while active:city = input(prompt)if city == 'quit':breakelse:print("I'd love to go to " + city.title() + "!")運(yùn)行程序:
Please enter the name of a city you have visited: Enter 'quit' when you are finished.Shanghai I'd love to go to Shanghai!Please enter the name of a city you have visited: Enter 'quit' when you are finished.Beijing I'd love to go to Beijing!Please enter the name of a city you have visited: Enter 'quit' when you are finished.quit在任何Python循環(huán)中都可以使用break語句,例如,可以使用break語句來退出遍歷列表或字典
【6.2.5】在循環(huán)中使用 continue
要返回到循環(huán)開頭,并根據(jù)條件測試結(jié)果決定是否繼續(xù)執(zhí)行循環(huán),可使用 continue 語句,它不像 break 語句那樣不再執(zhí)行余下的代碼并退出整個循環(huán),例如,從1到10只打印其中奇數(shù):
number =0 while number < 10:number += 1if number % 2 == 0:continueprint(number)輸出結(jié)果如下:
1 3 5 7 9【6.3】使用 while 循環(huán)來處理列表和字典
for循環(huán)是一種遍歷列表的有效方式,但在for循環(huán)中不應(yīng)修改列表,否則將導(dǎo)致Python難以跟蹤其中的元素,要在遍歷列表的同時對其進(jìn)行修改,可使用while循環(huán)
【6.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())首先創(chuàng)建一個未驗(yàn)證用戶列表,其中包含用戶Alice、Brian和Candace,還創(chuàng)建了一個空列表,用于存儲已驗(yàn)證的用戶,程序中的 while 循環(huán)將不斷地運(yùn)行,直到列表 unconfirmed_users 變成空的。在這個循環(huán)中,函數(shù)pop() 以每次一個的方式從列表 unconfirmed_users 末尾刪除未驗(yàn)證的用戶。由于Candace位于列表 unconfirmed_users 的末尾,因此其名字將首先被刪除、存儲到變量 current_user 中并加入到列表 confirmed_users 中。接下來是Brian,然后是Alice
為模擬用戶驗(yàn)證過程,我們打印一條驗(yàn)證消息并將用戶加入到已驗(yàn)證用戶列表中。未驗(yàn)證用戶列表越來越短,而已驗(yàn)證用戶列表越來越長。未驗(yàn)證用戶列表為空后結(jié)束循環(huán),再打印已驗(yàn)證用戶列表:
Verifying user: Candace Verifying user: Brian Verifying user: AliceThe following users have been confirmed: Candace Brian Alice【6.3.2】刪除包含特定值的所有列表元素
可以使用方法 remove() 來刪除列表中特定的值,但如果要刪除的值在列表中出現(xiàn)了多次,方法 remove() 就不管用了,如果要刪除列表中所有包含特定值的元素則可以使用 while 循環(huán):
names = ['alice' , 'candace' , 'alice' , 'brian' , 'alix' , 'candace' , 'heliy'] print(names) while 'candace' in names:names.remove('candace') print(names)輸出結(jié)果如下:
['alice', 'candace', 'alice', 'brian', 'alix', 'candace', 'heliy'] ['alice', 'alice', 'brian', 'alix', 'heliy']使用方法 remove() 做對比:
names = ['alice' , 'candace' , 'alice' , 'brian' , 'alix' , 'candace' , 'heliy'] print(names) names.remove('candace') print(names)輸出結(jié)果如下:
['alice', 'candace', 'alice', 'brian', 'alix', 'candace', 'heliy'] ['alice', 'alice', 'brian', 'alix', 'candace', 'heliy']【6.3.3】使用用戶輸入來填充字典
responses = {}#設(shè)置一個標(biāo)志,指出調(diào)查是否繼續(xù) polling_active = Truewhile polling_active:#提示輸入被調(diào)查者的姓名和回答name = input("\nWhat's your name?")response = input("What kind of fruit do you like?")#將答卷儲存在字典中responses[name] = response#詢問是否還有其他人要參與回答repeat = input("Would you like to let another person respond?(Yes/No)")if repeat == 'No':polling_active = False#調(diào)查結(jié)束,顯示結(jié)果 print("\n------ Poll Results ------") for name , response in responses.items():print(name + " like " + response + ".")運(yùn)行程序:
What's your name?TRHX What kind of fruit do you like?apple Would you like to let another person respond?(Yes/No)YesWhat's your name?TRHXCC What kind of fruit do you like?banana Would you like to let another person respond?(Yes/No)No------ Poll Results ------ TRHX like apple. TRHXCC like banana.總結(jié)
以上是生活随笔為你收集整理的Python3 基础学习笔记 C06【用户输入和 while 循环】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浦发万用随借金提前还 万用随借金提前还款
- 下一篇: 【Python CheckiO 题解】T