第 7 章講了用戶輸入 input( ) 和 while 循環,內容以下python
input( ) 工做原理app
超過一行的 input( )ide
int( ) 來獲取數字的輸入,進行比較函數
求模運算測試
簡單的 while 循環。我本身的理解就是設定一個條件,while 知足這個條件開始循環,不知足退出ui
break 直接退出spa
continue 跳出當前層的循環ci
避免無限循環rem
while 在列表中的應用字符串
while 刪除列表中指定的字符串 remove()
用戶輸入的字符來填充字典
input( ) 工做原理
首先定義 input( ) 函數括號中向用戶顯示提示說明,讓用戶輸入內容
在將用戶輸入的內容保存到變量 message 中,最後打印
-------------------------------------------------------------------------------------------
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
-------------------------------------------------------------------------------------------
Tell me something, and I will repeat it back to you: haha
haha
編寫清晰的程序
---------------------------------------------------------
name = input("Please enter your name: ")
print("Hello, " + name + "!")
---------------------------------------------------------
Please enter your name: python
Hello, python!
超過一行的 input
若是想打印多行提示信息,能夠使用 +=
-------------------------------------------------------------------------------------------
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")
-------------------------------------------------------------------------------------------
If you tell us who you are, we can personalize the message you see.
What is your first name? python
Hello, python!
使用 int( ) 來獲取數值輸入
若是不指定 age=int(age),python將會報錯
-------------------------------------------
age = input("How old are you? ")
print(age)
age = int(age)
if age >= 18:
print(age)
-------------------------------------------
How old are you? 29
29
29
int( ) 進行數值比較,進行測試
--------------------------------------------------------------------------------
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
--------------------------------------------------------------------------------
How tall are you, in inches? 89
You're tall enough to ride!
求膜運算符
兩個數相除,返回餘數
---------------------
print(4 % 3)
print(5 % 3)
print(6 % 3)
print(7 % 3)
----------------------
1
2
0
1
能夠利用求模來計算一個數是奇數仍是偶數
-------------------------------------------------------------------------------------------
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
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: 78
The number 78 is even.
while 循環
若是 while 小於等於 5,就一直運行
打印一次後,就將 current_number 的數值 +1
--------------------------------------
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
--------------------------------------
1
2
3
4
5
讓用戶選擇什麼時候退出
若是用戶不輸入 quit,就一直循環下去
-------------------------------------------------------------------------------------
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. zhao
zhao
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. shanshan
shanshan
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
quit
進行更改
上面的程序在用戶輸入 quit 時,也會將 quit 做爲消息在打印一遍
代碼中並無定義若是用戶輸入 quit 會怎麼樣,因此當用戶輸入 quit
直接結束循環,退出
-------------------------------------------------------------------------------------
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. zhao
zhao
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
繼續改進上面的代碼
就像剛纔說的,並無指定若是用戶輸入 quit 會怎麼樣
其實在 while 循環中嵌套一個 if-else 語句就能夠了
可是開始循環時,先定義一個 active=True
若是是 True 就循環,是 False 就中止循環
------------------------------------------------------------------------------------
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)
------------------------------------------------------------------------------------
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. zhao
zhao
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
break 直接退出循環
仍是以上面的代碼爲例,當用戶輸入 break 時,直接 break,結束當前的 while 循環
-----------------------------------------------------------------------------------
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"
while True:
city = input(prompt)
if city == 'quit':
break
else:
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.)zhao
I'd love to go to Zhao!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)shushu
I'd love to go to Shushu!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)quit
continue 跳出當前的循環
每循環一次就 +1,當 current_number 能夠被 2 整除的時候
就執行 continue,跳出這一層循環,繼續 while 的下一次循環
------------------------------------------
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
------------------------------------------
1
3
5
7
9
避免無限循環
死循環代碼以下,x 開始等於 1,在第一次循環結束後並無變,
一直等於 1,永遠知足 x <= 5 的條件,因此會被一直打印
------------------
x = 1
while x <= 5:
print(x)
------------------
正常代碼
須要指定一個條件,每循環一次 x 的值都 +1
------------------
x = 1
while x <= 5:
print(x)
x += 1
------------------
while 在列表中的應用
-----------------------------------------------------------------------
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
刪除包含特定值的全部列表元素
while 中一直執行 remove( ) 刪除列表中的 cat 字符
----------------------------------------------------------------------
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']
用戶輸入來填充字典
定義一個空的字典 responses
定義 polling_active = True 開始循環,等於 False 退出循環
讓用戶分別輸入 name,response
responses[name] = response 將用戶輸入的添加到 responses 字典中
for 循環 items( ) 遍歷 responses 字典
-------------------------------------------------------------------------------------------
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("Would you like to let another person respind? (yes/ no) ")
if repeat == 'no':
polling_active = False
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
-------------------------------------------------------------------------------------------
What is your name? shanshan
Which mountain would you like to climb someday? taiqiu
Would you like to let another person respind? (yes/ no) no
--- Poll Results --- shanshan would like to climb taiqiu .