1. 程式人生 > >python的基礎05 if語句

python的基礎05 if語句

if語句

5.1 一個簡單的示例

cars = ['audi','bmw','subaru','toyota']
for car in cars:
    if car == 'bmw':  # 檢查car是否是bmw,如果是就以首字母大寫的方式列印
        print(car.title())
    
else: # 如果不是就以全部字母大寫的方式列印 print(car.upper())
AUDI
Bmw
SUBARU
TOYOTA
 

5.2 條件測試

  • 每條if語句的核心都是一個值為True或者False的表示式,這種表示式稱為條件測試.
  • python根據條件測試的值為True還是False來決定是否執行if語句中的程式碼.
  • 如果條件測試的值為True,python會執行緊跟在if語句後面的程式碼.
  • 如果為False,python就會忽略這些程式碼.

    5.2.1 檢查是否相等

# 最簡單的條件測試是檢查兩個變數的值是否相等
car = 'bmw'
print(car == 'bmw')
car = 'audi'
print
(car == 'bmw')
True
False
 

5.2.2 檢查是否相等時不考慮大小寫

  • 在python中檢查是否相等時區分大小寫
car = 'AUDI'
print(car == 'audi') # 大小寫不一樣,結果為False
# lower()讓car的值全部小寫,所以AUDI變為了audi,再把轉化的結果audi和==右邊的audi相比較
print(car)
print(car.lower() == 'audi') 
False
AUDI
True
 

5.2.3 檢查是否不相等

  • 要的判斷兩個值是否不相等我們使用(!=)
# 使用if語句來演示如何使用不等運算子
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
    print("Hold the anchovies!")
Hold the anchovies!
 

5.2.4 比較數字

 

age = 18 
print(age == 18)
age = 19
print(age != 18)
age = 25
print(age > 18)
print(age < 18)
print(age % 3 == 1)

 

True
True
True
False
True
 

5.2.5 檢查多個條件

  • 有時候需要比較兩個條件都為True時才執行相應的操作,而有時候只需要一個條件的結果為True就執行相應的操作,這個時候我們可以使用關鍵字and和or

    1.使用and檢查多個條件

  • 要檢查是否兩個條件都為True,可以使用and將兩個條件測試合而為一
    • 如果每個測試都通過了,整個表示式的結果就是True
    • 如果至少有一個測試沒有通過,整個表示式的結果就是False
# 檢查兩個人的年齡都不小於21
age_0 = 22
age_1 = 18
print(age_0 >= 21 and age_1 >= 21)
age_1 = 21
print((age_0 >= 21) and (age_1 >= 21))
False
True
 

2.使用or檢查多個條件

  • 關鍵字or也能夠讓我們檢查多個條件,但至少有一個條件滿足,就能通過整個測試
  • 僅當兩個測試都沒有通過時,使用or的表示式才為False
age_0 = 22
age_1 = 18
print((age_0 >= 21) or (age_1 >= 21))
age_0 = 16
print((age_0 >= 21) or (age_1 >= 21))
True
False
 

5.2.6 檢查特定值是否包含在列表中

  • 要判斷特定的值是否包含在列表中,可使用關鍵字in
# in練習
requested_toppings = ['mushrooms','onions','pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)
True
False
 

5.2.7 檢查特定值是否不包含在列表中

  • 檢查特定值是否不包含在列表中,我們使用關鍵字not in
# not in 練習
banned_users = ['andrew','carolina','david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ",you can post a response if you wish.")
Marie,you can post a response if you wish.
 

5.2.8 布林表示式

  • 與條件表示式一樣,布林表示式的結果要麼為True,要麼為False.
  • 布林值通常用於記錄條件,在跟蹤程式狀態中重要的條件方面,布林值提供了一種高效的方式
 

5.3 if語句

  • if語句有很多種,選擇哪種取決於我們要測試嘚瑟條件數.
  • if 條件表示式:最簡單的if語句只有一個測試和操作.
    • 條件表示式就是計算結果必須為布林值的表示式
    • 表示式後面的冒號(:)必須有,不能少
    • 注意if後面的程式碼塊(我們把縮排相同的語句稱之為程式碼塊),如果屬於if語句,則必須使用同一個縮排等級
    • 條件表示式的結果為True則執行if後面的語句塊

      5.3.1 簡單的if語句

  • 最簡單的if語句只有一個測試和操作.
age = 19
if age > 18:  # 表示式的結果為True,所以會執行下面的print
    print("You are old enough to vote")
    print("Have you registered to vote yet?")
    
# 練習2
age = 17  # 把17賦值給age
if age < 18:  # if空格+條件表示式. 因為年齡17 < 18,結果為True,所以會執行下面的語句快
    print("\n對不起!")
    print("你未滿十八歲")
    print("你不能待在這裡")
print("歡迎你老這裡玩")
You are old enough to vote
Have you registered to vote yet?

對不起!
你未滿十八歲
你不能待在這裡
歡迎你老這裡玩
 

5.3.2 if-else語句

  • 經常需要在條件測試通過時執行一些操作,並且在沒有通過時執行另一個操作,在這種情況下我們使用if-else語句.
    • 雙向分支有兩個分支,當程式執行到if...else..的時候,一定會執行其中的一個,也僅僅執行其中的一個
    • 縮排的問題,if和else屬於一個層級,其餘語句一個層級
age = 17
if age >= 18:  # 條件表示式的結果為False,所以不會執行if的縮排語塊,而是執行else語塊
    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!
 

5.3.3 if-elif-else結構

  • 經常需要檢查查過兩個的情形,這種情況我們使用if-elif-else結構.
  • python只會執行if-elif-else結構中的一個程式碼塊.
  • python會一次檢查每個條件測試,直到遇到了通過的條件測試,python會執行緊跟在它後面的程式碼,而跳過餘下的測試. 
# 遊樂園收費規則
# 四歲以下免費,4-18收費5美元,大於等於18歲收費10美元
age = 12
if age < 4: # 條件測試結果為False,不會執行緊跟在它後面的語句
    print("You admission cost is $0.")
elif age >= 4 and age < 18: # 條件測試的結果是True,執行緊跟語句,忽略else.
    print("You admission cost is $5.")
else:
    print("You admission cost is $10")

# 修改上述程式碼
age = 12
if age < 4:
    price = 0
elif 4 <= age < 18:
    price = 5
else:
    price = 10
print("Your admission cost is $" + str(price) + '.')
You admission cost is $5.
Your admission cost is $5.
 

5.3.4 使用多個elif程式碼塊

  • 可根據需要使用多個的elif程式碼塊
age = 68
if age < 4:
    price = 0
elif 4 <= age < 18:
    price = 5
elif age >= 65:
    price = 5
else:
    price = 10
print("Your admission cost is $" + str(price) + '.')
  Your admission cost is $5.  

5.3.6 測試多個條件

  • 有時候必須檢查我們關心的所有條件,在這種情況下,應該使用一系列不包含elif和else程式碼塊的簡單的if語句.
  • 在可能有多個條件為True,且我們需要在每個條件為True時都執行相應的措施,適合使用這種方法.
requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
    print(1)
if 'pepperoni' not in requested_toppings:
    print(2)
if 'extra cheese' in requested_toppings:
    print(3)
1
2
3
 

動手試一試 

 
           
           
#5-3 外星人顏色 #1:假設在遊戲中剛射殺了一個外星人,請建立一個名為alien_color 的變數,並將其設定為'green'、 'yellow'或'red'。
alien_color = 'green'
# 編寫一條 if 語句,檢查外星人是否是綠色的;如果是,就列印一條訊息,指出玩家獲得了 5 個點。
if alien_color == 'green':
    print("你獲得了5個.")
# 編寫這個程式的兩個版本,在一個版本中上述測試通過了,而在另一個版本中未通過(未通過測試時沒有輸出)。
alien_color = 'yellow'
if alien_color == 'green':
    print(1)

'''5-4 外星人顏色#2:像練習 5-3 那樣設定外星人的顏色,並編寫一個 if-else 結構。
 如果外星人是綠色的,就列印一條訊息,指出玩家因射殺該外星人獲得了 5 個
點。
 如果外星人不是綠色的,就列印一條訊息,指出玩家獲得了 10 個點。
 編寫這個程式的兩個版本,在一個版本中執行 if 程式碼塊,而在另一個版本中執
行 else 程式碼塊。'''
# 1
alien_color = 'yellow'
if alien_color == 'green':
    print("你獲得了5個點")
else:
    print("你獲得了10個點")
# 2
alien_color = 'green'
if alien_color != 'yellow':
    print("恭喜你獲得了5個點")
else:
    print("你獲得了5個點")
'''5-5 外星人顏色#3:將練習 5-4 中的 if-else 結構改為 if-elif-else 結構。
 如果外星人是綠色的,就列印一條訊息,指出玩家獲得了 5 個點。
 如果外星人是黃色的,就列印一條訊息,指出玩家獲得了 10 個點。
 如果外星人是紅色的,就列印一條訊息,指出玩家獲得了 15 個點。'''
alien_color = 'green'
if alien_color == 'green':
    print("你獲得了5個點")
elif alien_color == 'yellow':
    print("你獲得了10個點")
else:
    print("你獲得了15個點")
你獲得了5個.
你獲得了10個點
恭喜你獲得了5個點
你獲得了5個點
 
'''5-6 人生的不同階段: 設定變數 age 的值, 再編寫一個 if-elif-else 結構, 根據 age
的值判斷處於人生的哪個階段。
 如果一個人的年齡小於 2 歲,就列印一條訊息,指出他是嬰兒。
 如果一個人的年齡為 2(含)~4 歲,就列印一條訊息,指出他正蹣跚學步。
 如果一個人的年齡為 4(含)~13 歲,就列印一條訊息,指出他是兒童。
 如果一個人的年齡為 13(含)~20 歲,就列印一條訊息,指出他是青少年。
 如果一個人的年齡為 20(含)~65 歲,就列印一條訊息,指出他是成年人。
 如果一個人的年齡超過 65(含) 歲,就列印一條訊息,指出他是老年人。'''
age = 35
if age < 2:
    print("他是嬰兒")
elif age >= 2 and age < 4:
    print("他正在學走路")
elif 4 <= age < 13:
    print("他是兒童")
elif(age >= 13) and (age < 20):
    print("他是青少年")
elif 20 <= age < 65:
    print("他是成年人")
else:
    print("他是老年人")
他是成年人
 
#5-7 喜歡的水果:建立一個列表,其中包含你喜歡的水果,再編寫一系列獨立的 if語句,檢查列表中是否包含特定的水果。
fruit = ['apple','pear','banana']
if 'pear' in fruit:
    print("pear在裡面")
    
#  將該列表命名為 favorite_fruits,並在其中包含三種水果。
favorite_fruits = ['apple','pear','banana']
# 編寫 5 條 if 語句,每條都檢查某種水果是否包含在列表中,如果包含在列表中,就列印一條訊息,如“ You really like bananas!”。
if 'apple' in favorite_fruits:
    print('You really like apple!')
if 'banana' in favorite_fruits:
    print("You really like bananas")
if 'pear' in favorite_fruits:
    print('You really like pear!')
if 'orange' in favorite_fruits:
    print('You really like bananas!')
if 'watermellon' in favorite_fruits:
    print('You really like bananas!')
pear在裡面
You really like apple!
You really like bananas
You really like pear!
 

5.4 使用if語句處理列表

5.4.1 檢查特殊元素

 

requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
    print("Adding " + requested_topping + '.')
print("\nFinished making your pizza!")

 

    Adding mushrooms.
Adding green peppers.
Adding extra cheese.

Finished making your pizza!
 
# 在for迴圈中包含if語句
# 如果青椒用完了,告訴顧客我們沒有青椒了
requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
    if requested_topping == 'green pepers':
        print("Sorry,we are out of green pepers right now.")
    else:
        print("Adding " + requested_topping + '.')
print("\nFinished making your pizza!")
Adding mushrooms.
Adding green peppers.
Adding extra cheese.

Finished making your pizza!
 

5.4.2 確定列表不是空的

# 建立了一個空的列表
resuested_toppings = []
# 在if語句中,將列表名用在條件表示式時,python將在列表中包含一個元素時返回True,並在列表為空時返回False.
if requested_toppings:  # 因為是一個空列表,所以python不會執行下面這個for迴圈
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")
Are you sure you want a plain pizza?
 

5.4.3 使用多個列表 

# 我們定義了一個列表,其中包含比薩店供應的配料
available_toppings = ['mushrooms','olives','green pepers','pepperoni','pineapple','extra cheese']
# 定義了一個列表,其中包含顧客點的配料
requested_tippings = ['mushrooms','french fries','extra cheese']
# 遍歷顧客點的配料列表。在這個迴圈中,對於顧客點的每種配料,我們都檢查它是否包含在供應的配料列表中
for requested_topping in requested_toppings:
# 如果這個原料在available_toppings中,就將其加入到比薩中,否則將執行else程式碼塊
    if requested_topping in available_toppings:
        print("Adding " + requested_topping + ".")
    else:
        print("Sorry,we don't have " + requested_topping + '.')
print("\nFinished making your pizza")
Adding mushrooms.
Sorry,we don't have french fries.
Adding extra cheese.

Finished making your pizza
 

動手試一試

'''5-8 以特殊方式跟管理員打招呼:建立一個至少包含 5 個使用者名稱的列表,且其中一
個使用者名稱為'admin'。想象你要編寫程式碼,在每位使用者登入網站後都列印一條問候訊息。
遍歷使用者名稱列表,並向每位使用者列印一條問候訊息。
 如果使用者名稱為'admin',就列印一條特殊的問候訊息,如“ Hello admin, would you
like to see a status report?”。
 否則,列印一條普通的問候訊息,如“ Hello Eric, thank you for logging in again”。'''
username = ['python','java','C','lucy','bob','admin']
if 'admin' in username:
    print('Hello admin,would you like to see a status report?')
else:
    print("Hello " + str(username) + ', thank you for logging in again.')

'''5-9 處理沒有使用者的情形:在為完成練習 5-8 編寫的程式中,新增一條 if 語句,檢
查使用者名稱列表是否為空。
 如果為空,就列印訊息“ We need to find some users!”。'''
usernames = ['python','java','C','lucy','bob','admin']
if usernames:
    for username in usernames:
        print("Hello,sir")
else:
    print('We need to find some users!')
#  刪除列表中的所有使用者名稱,確定將列印正確的訊息。  
usernames = []
if usernames:
    for username in usernames:
        print("Hello,sir")
else:
    print('We need to find some users!')
Hello admin,would you like to see a status report?
Hello,sir
Hello,sir
Hello,sir
Hello,sir
Hello,sir
Hello,sir
We need to find some users!
 
#5-10 檢查使用者名稱:按下面的說明編寫一個程式,模擬網站確保每位使用者的使用者名稱都獨一無二的方式。
#  建立一個至少包含 5 個使用者名稱的列表,並將其命名為 current_users。
current_users = ['1','22','juy','498','3247']
# 再建立一個包含 5 個使用者名稱的列表,將其命名為 new_users,並確保其中有一兩個使用者名稱也包含在列表 current_users 中。
new_users= ['1','22','JUY','34','549']
'''遍歷列表 new_users,對於其中的每個使用者名稱,都檢查它是否已被使用。如果是這樣,就列印一條訊息,指出需要輸入別的使用者名稱;否則,列印一條訊息,指
出這個使用者名稱未被使用。'''
for new_user in new_users:
    new_user = new_user.title()
    if new_user in current_users:
        print("這個使用者名稱已經被使用了")
    else:
        print("你可以使用這個使用者名稱")
#確保比較時不區分大訊息;換句話說,如果使用者名稱'John'已被使用,應拒絕使用者名稱'JOHN'。
這個使用者名稱已經被使用了
這個使用者名稱已經被使用了
你可以使用這個使用者名稱
你可以使用這個使用者名稱
你可以使用這個使用者名稱
 
'''5-11 序數:序數表示位置,如 1st 和 2nd。大多數序數都以 th 結尾,只有 1、 2 和 3
例外。
 在一個列表中儲存數字 1~9。
 遍歷這個列表。
 在迴圈中使用一個 if-elif-else 結構,以列印每個數字對應的序數。輸出內容
應為 1st、 2nd、 3rd、 4th、 5th、 6th、 7th、 8th 和 9th, 但每個序數都獨佔一行。'''
numbers = list(range(1,10))
for number in numbers:
    number = str(number)
    if number == '1':
        print(number + "st")
    if number == '2':
        print(number + "nd")
    elif number == '3':
        print(number + 'rd')
    else:
        print(number + 'th')
1st
1th
2nd
3rd
4th
5th
6th
7th
8th
9th