日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python3 基础学习笔记 C06【用户输入和 while 循环】

發布時間:2023/12/10 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python3 基础学习笔记 C06【用户输入和 while 循环】 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

CSDN 課程推薦:《8小時Python零基礎輕松入門》,講師齊偉,蘇州研途教育科技有限公司CTO,蘇州大學應用統計專業碩士生指導委員會委員;已出版《跟老齊學Python:輕松入門》《跟老齊學Python:Django實戰》、《跟老齊學Python:數據分析》和《Python大學實用教程》暢銷圖書。


Python3 基礎學習筆記第六章【用戶輸入和 while 循環】

目錄

  • 【6.1】函數 input() 的工作原理
    • 【6.1.1】使用 int() 來獲取數值輸入
    • 【6.1.2】求模運算符
    • 【6.1.3】在 Python 2.7 中獲取輸入
  • 【6.2】while 循環
    • 【6.2.1】使用 while 循環
    • 【6.2.2】讓用戶選擇退出循環
    • 【6.2.3】使用標志
    • 【6.2.4】使用 break 退出循環
    • 【6.2.5】在循環中使用 continue
  • 【6.3】使用 while 循環來處理列表和字典
    • 【6.3.1】在列表之間移動元素
    • 【6.3.2】刪除包含特定值的所有列表元素
    • 【6.3.3】使用用戶輸入來填充字典


【6.1】函數 input() 的工作原理

函數 input() 讓程序暫停運行,等待用戶輸入一些文本。獲取用戶輸入后,Python將其儲存在一個變量當中,以方便你使用;函數 input() 返回為 string 類型

message = input("Please tell me your name:") print("Hello , " + message + "!")

輸出結果如下:

Please tell me your name:anliy Hello , anliy!

進階:

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 + "!")

輸出結果如下:

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() 來獲取數值輸入

使用函數 input() 時,Python會將用戶輸入解讀為字符串:

>>> age = input("How old are you?") How old are you?19 >>> age '19'

為了解決這個問題,可以使用函數 int() ,它讓Python將輸入視為數值:

>>> age = input("How old are you?") How old are you?19 >>> age = int(age) >>> age 19

實例:

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!")

輸出結果如下:

Please tell me your age:17 You are not old enough to go to Internet bar!

【6.1.2】求模運算符

處理數值信息時,求模運算符(%)是一個很有用的工具,它將兩個數相除并返回余數:

>>> 4 % 3 1 >>> 5 % 3 2 >>> 8 % 2 0 >>> 7 % 3 1

【6.1.3】在 Python 2.7 中獲取輸入

如果使用 Python 2.7,應該使用函數 raw_input() 來提示用戶輸入,這個函數與 Python 3 中的 input() 一樣,也將輸入解讀為字符串;Python 2.7 也包含函數 input(),但它將用戶輸入解讀為Python代碼,并嘗試運行它們

【6.2】while 循環

for 循環用于針對集合中的每一個元素的一個代碼塊,而 while 循環不斷地運行,直到指定的條件不滿足為止

【6.2.1】使用 while 循環

一個簡單的 while 循環:

num = 1 while num < 5:print(num)num += 1

輸出結果如下:

1 2 3 4

【6.2.2】讓用戶選擇退出循環

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)

運行程序:

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】使用標志

在要求很多條件都滿足才繼續運行的程序中,可以定義一個變量,用于判斷整個程序是否處于活動狀態,這個變量稱為標志

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)

運行結果與6.2.2一致

【6.2.4】使用 break 退出循環

要立即退出 while 循環,不再運行循環中余下的代碼,也不管條件測試的結果如何,可使用 break 語句,break 語句用于控制程序流程,可使用它來控制哪些代碼將執行,哪些代碼不執行

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() + "!")

運行程序:

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循環中都可以使用break語句,例如,可以使用break語句來退出遍歷列表或字典

【6.2.5】在循環中使用 continue

要返回到循環開頭,并根據條件測試結果決定是否繼續執行循環,可使用 continue 語句,它不像 break 語句那樣不再執行余下的代碼并退出整個循環,例如,從1到10只打印其中奇數:

number =0 while number < 10:number += 1if number % 2 == 0:continueprint(number)

輸出結果如下:

1 3 5 7 9

【6.3】使用 while 循環來處理列表和字典

for循環是一種遍歷列表的有效方式,但在for循環中不應修改列表,否則將導致Python難以跟蹤其中的元素,要在遍歷列表的同時對其進行修改,可使用while循環

【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())

首先創建一個未驗證用戶列表,其中包含用戶Alice、Brian和Candace,還創建了一個空列表,用于存儲已驗證的用戶,程序中的 while 循環將不斷地運行,直到列表 unconfirmed_users 變成空的。在這個循環中,函數pop() 以每次一個的方式從列表 unconfirmed_users 末尾刪除未驗證的用戶。由于Candace位于列表 unconfirmed_users 的末尾,因此其名字將首先被刪除、存儲到變量 current_user 中并加入到列表 confirmed_users 中。接下來是Brian,然后是Alice

為模擬用戶驗證過程,我們打印一條驗證消息并將用戶加入到已驗證用戶列表中。未驗證用戶列表越來越短,而已驗證用戶列表越來越長。未驗證用戶列表為空后結束循環,再打印已驗證用戶列表:

Verifying user: Candace Verifying user: Brian Verifying user: AliceThe following users have been confirmed: Candace Brian Alice

【6.3.2】刪除包含特定值的所有列表元素

可以使用方法 remove() 來刪除列表中特定的值,但如果要刪除的值在列表中出現了多次,方法 remove() 就不管用了,如果要刪除列表中所有包含特定值的元素則可以使用 while 循環:

names = ['alice' , 'candace' , 'alice' , 'brian' , 'alix' , 'candace' , 'heliy'] print(names) while 'candace' in names:names.remove('candace') print(names)

輸出結果如下:

['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)

輸出結果如下:

['alice', 'candace', 'alice', 'brian', 'alix', 'candace', 'heliy'] ['alice', 'alice', 'brian', 'alix', 'candace', 'heliy']

【6.3.3】使用用戶輸入來填充字典

responses = {}#設置一個標志,指出調查是否繼續 polling_active = Truewhile polling_active:#提示輸入被調查者的姓名和回答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#調查結束,顯示結果 print("\n------ Poll Results ------") for name , response in responses.items():print(name + " like " + response + ".")

運行程序:

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.

總結

以上是生活随笔為你收集整理的Python3 基础学习笔记 C06【用户输入和 while 循环】的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。