python基礎 (3)if 和 while的使用

weixin_51924047發表於2020-12-12

學習內容:

1.if語句
2.使用者輸入和while迴圈

一.if語句

(1)1.簡單的if語句:
格式:

if conditional_test:
 do something 

在第1行中,可包含任何條件測試,而在緊跟在測試後面的縮排程式碼塊中,可執行任何操作。
如果條件測試的結果為True,Python就會執行緊跟在if語句後面的程式碼;否則Python將忽略這些程式碼。
例如:

age = 19
if age >= 18:
   print("You are old enough to vote!") 

執行結果為:

You are old enough to vote!

2.if-else語句:
經常需要在條件測試通過了時執行一個操作,並在沒有通過時執行另一個操作;在這種情況下,可使用Python提供的if-else語句。
例如:

age = 17
if age >= 18:
  print("You are old enough to vote!")
  print("Have you registered to vote yet?")
else:
  print("Sorry, you are too young to vote.")
  print("Please register to vote as soon as you turn 18!")

執行結果為:

Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!

3.if-elif-else語句:
Python只執行if-elif-else結構中的一個程式碼塊(即if或elif或else中的為真語句),它依次檢查每個條件測試,直到遇到通過了的條件測試。
例如:

age = 12
if age < 4:
 print("Your admission cost is $0.")
elif age < 18:
 print("Your admission cost is $5.")
else:
 print("Your admission cost is $10.")

執行結果為:

Your admission cost is $5.

也可以使用多個elif的程式碼塊
例如:

age = 12
if age < 4:
 price = 0
elif age < 18:
 price = 5
elif age < 65:
 price = 10
else:
 price = 5
print("Your admission cost is $" + str(price) + ".") 

執行結果為:

Your admission cost is $5.

同時模組中也可以省略else改用elif。
if-elif-else結構功能強大,但僅適合用於只有一個條件滿足的情況:遇到通過了的測試後,Python就跳過餘下的測試。這種行為很好,效率很高,讓你能夠測試一個特定的條件。
4.測試多個條件:
使用一系列不包含elif和else程式碼塊的簡單if語句。在可能有多個條件為True,且你需要在每個條件為True時都採取相應措施
時,適合使用這種方法。
例如:

 requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
 print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
 print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
 print("Adding extra cheese.")

print("\nFinished making your pizza!") 

執行結果為:

Adding mushrooms.
Adding extra cheese.
Finished making your pizza!

if-elif-else情況下:

requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
 print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
 print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
 print("Adding extra cheese.")

print("\nFinished making your pizza!") 

執行結果為:

Adding mushrooms.
Finished making your pizza!

在倆者的對比之下,更易體會何時使用何種語句。
(2)使用if語句處理列表
1.檢查列表中特殊元素:
例如:

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
 print("Sorry, we are out of green peppers right now.")
else:
 print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!") 

執行結果為:

Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!

這樣就可以找出列表中的特殊元素。
2.確定列表不為空:
在if語句中將列表名用在條件表示式中時,Python將在列表
至少包含一個元素時返回True,並在列表為空時返回False。
例如:

requested_toppings = []
if requested_toppings:
 print("\nFinished making your pizza!")
else:
 print("Are you sure you want a plain pizza?")

執行結果為:

Are you sure you want a plain pizza? 

二.使用者輸入和while迴圈

(1)input()函式
1.input()函式原理:函式input()讓程式暫停執行,等待使用者輸入一些文字。獲取使用者輸入後,Python將其儲存在一個變數中,以方便你使用。
函式input()接受一個引數:即要向使用者顯示的提示或說明,讓使用者知道該如何做。
例如:

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: Hello everyone!
Hello everyone! 

2.使用int()來獲取數值輸入:
使用函式input()時,Python將使用者輸入解讀為字串。然後要得到我們需要的值(整型,浮點型等)就需要強制轉換。
用法:int(input())
(2)while迴圈
1.首先迴圈是什麼結構組成,其次如何使用迴圈,迴圈可以幹什麼。
迴圈結構:測試條件+迴圈體
例如:

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

執行結果:

1
2
3
4
5 

以上為一個列印1到5的簡單迴圈。
2.while迴圈break語句:
當程式執行遇到break時將會退出迴圈結構。

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.) New York
I'd love to go to New York!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) San Francisco
I'd love to go to San Francisco!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit 

3.使用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

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

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
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 respond? (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? Eric
Which mountain would you like to climb someday? Denali
Would 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
Would you like to let another person respond? (yes/ no) no
--- Poll Results ---
Lynn would like to climb Devil's Thumb.
Eric would like to climb Denali. 

相關文章