python 使用者輸入和while迴圈

2021-09-26 23:22:17 字數 3047 閱讀 3607

while迴圈

使用break退出迴圈

在迴圈中使用continue

避免無限迴圈

使用while迴圈來處理列表和字典

函式input()的工作原理

函式input()讓程式暫停執行,等待使用者輸入一些文字。獲取使用者輸入後,python將其儲存在乙個變數中,以方便你使用。

message=input("please input")

print(message)

使用函式input()時,都應指定清晰而易於明白的提示,有時候提示可能超過一行,在這種情況下,可將提示儲存在乙個變數中,再將變數傳遞給函式input()

message=「if you tell us who you are , we can personalize the message you see"

message+="\nwhat is you first name?"

name=input(message)

print("\nhello, "+name+"!")

這個示例演示了一種建立多行字串的方式。第一行將訊息儲存在變數message中;

在第二行,運算子+=在儲存在message中的字串末尾附加乙個字串。

使用int()來獲取數值輸入

使用函式input()時,python將使用者輸入解讀為字串。

輸入數字也能成功列印輸出,但是要是做其他數值比較就會報錯。

為了解決這個可以使用函式int(),它讓python將輸入視為數值。函式int()將數字的字串表示轉換為數值表示。

>>>age=input("how old are you?")

how old are you? 26

>>>age=int(age)

>>>age>=18

true

求模運算子

處理數值資訊時,求模運算子(%)是乙個很有用的工具,它將兩個數相除並返回餘數。

>>>4%3

1>>>5%3

2

求模運算子不會指出乙個數是另乙個數的多少倍,而只指出餘數是多少。

如果乙個數被另乙個數整出,餘數就為0,求模運算子將返回0,可利用這個來判斷乙個數是奇數還是偶數。

for迴圈是對每個列表中的元素都執行相同的操作,

而while迴圈是不斷地執行,直到指定的條件不滿足為止。

number=1

while number<=5:

print(number)

number += 1

number=number+1

要立即退出while迴圈,不再執行迴圈中餘下的**,也不管條件測試的結果如何,可使用break語句。

break語句用於控制程式流程

message="please enter the name fo a city"

message+="(enter 'quit' when you are finished)"

while true:

city=input(message)

if city == 'quit':

break

else:

print("i love " + city)

注意:在python任何迴圈中都可以使用break語句。例如,可使用break語句來退出遍歷列表或字典的for迴圈。

要返回到迴圈開頭,忽略餘下的**,並根據條件測試結果決定是否繼續執行迴圈,可使用continue語句。

例如:列印1到10的奇數

number=0

while number<10

number+=1

if number % 2 ==0:

continue #滿足number%2==0,則繼續返回上面開始迴圈,不滿足則輸出下面的print語句。

print(number)

要避免寫出無限迴圈,務必對每個while迴圈進行測試,確保它按預期那樣結束。如果你希望程式在使用者輸入特定值時結束,可執行程式並輸入那樣的值;如果在這種情況下程式沒有結束,請檢查程式處理這個值的方式,確認程式至少有乙個這樣的地方能讓迴圈條件為false或讓break語句得以執行。

在列表之間移動元素

unauth_users=['liming','xiaobai']           #未認證使用者

auth_users= #已認證使用者

while unauth_users:

user=unauth_users.pop()

print("auth_users:")

for auth_user in auth_users:

print(auth_user.title()

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

使用函式remove()刪除列表中的特定值,只能刪除第乙個指定的值,如果乙個值出現了多次,可使用while迴圈來刪除。

pets=['dogs','cat','dogs','cat']

while 'cat' in pets:

pets.remove('cat')

print(pets)

使用使用者輸入來填充字典
wenda={}

active=true #設定乙個標誌位,指出問答是否繼續

while active:

names=input("what is your name?")

ages=input("how old are you?")

wenda[names]=ages #將問答儲存在字典

message=input("who wants to quiz?(yes or no)")

if message =='no':

actuve=false

for name,age in wenda.items():

print(name+age)

Python入門筆記 迴圈for和while

while 迴圈 在給定的判斷條件為 true 時執行迴圈體,否則退出迴圈體。for 迴圈 重複執行語句 巢狀迴圈 你可以在while迴圈體中巢狀for迴圈 break 語句 在語句塊執行過程中終止迴圈,並且跳出整個迴圈 continue 語句 在語句塊執行過程中終止當前迴圈,跳出該次迴圈,執行下一...

python請求使用者輸入 使用者輸入

使用者輸入 大多數程式都旨在解決終端使用者的問題,為此通常需要從使用者那裡獲取一些資訊。例如,假設有人要判斷自己是否到了投票的年齡,要編寫回答這個問題的程式,就需要知道使用者的年齡,這樣才能給出 答案。因此,這種程式需要讓使用者輸入其年齡,再將其與投票年齡進行比較,以判斷使用者是否到了投票的年齡,再...

python使用者輸入

使用者輸入 python2.0 name raw input input your name raw input 輸入接收的是字串和數字,python都認為是字串。並賦值給name name input input your age input 輸入接收的是數字和字元,input python認為輸...