天天看點

小菜鳥的python學習之路(4)學習階梯

學習階梯

《Python程式設計:從入門到實踐》

  • 第一部分:基礎知識

第5章 if語句
  1. 一個簡單的示例

toppings.py

#周遊清單,并以首字母大寫的方式列印其中的汽車名,但對于汽車名'bmw',以全大寫的方式列印
cars = ['bmw', 'audi', 'toyota', 'subaru']
for car in cars:
    if car =='bmw':
        print(car.upper())
    else:
        print(car.title())
           
  1. 條件測試

每條if語句的核心都是一個值為True或False的表達式,這種表達式被稱為條件測試。Python

根據條件測試的值為True還是False來決定是否執行if語句中的代碼。

  • 檢查是否相等

一個等号是陳述;兩個等号是發問

car='bmw'
print(car=='bmw')

car='audi'
print(car=='bmw')
           
  • 檢查是否相等時考慮大小寫
car='bmw'
print(car=='bmw')
car='audi'
print(car=='bmw')
car='Audi'
print(car=='audi')
print(car.lower()=='audi')
           
  • 檢查是否不相等

要判斷兩個值是否不等,可結合使用驚歎号和等号(=),其中的驚歎号表示不

requested_topping='mushrooms'
if requested_topping!='anchovies':
    print("Hold the anchovies!")
           
  • 比較數字
age=18
print(age==18)

answer=17
if answer !=42:
    print("That is not the correct answer. Please try again!")

age=19
print(age<21)
print(age<=21)
print(age>21)
print(age>=21)
           
  • 檢查多個條件

使用關鍵字and和or,有時候需要在兩個條件都為True時才執行相應的操作,而有時候隻要求一個條件為True時就執行相應的操作。

#使用and檢查多個條件
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)
print((age_0>=21)and(age_1>=21))#加括号可以增強可讀性,但不是必須這樣做
           
#使用or檢查多個條件
age_0 = 22
age_1 = 18
print(age_0 >= 21 or age_1 >= 21)
age_0 = 18
print(age_0 >= 21 or age_1 >= 21)
           
  • 檢查特定值是否包含在清單中

要判斷特定的值是否已包含在清單中,可使用關鍵字in

requested_toppings=['mushrooms','onions','pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)
           
  • 檢查特定值是否不包含在清單中

确定特定的值是否未包含在清單可使用關鍵字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.")
           
  • 布爾表達式

布爾值通常用于記錄條件

game_active=True
can_edit=False
print(game_active)
print(can_edit)
           

練習

#5-1 條件測試:編寫一系列條件測試;将每個測試以及你對其結果的預測和實際結果都列印出來。你編寫的代碼應類似于下面這樣:
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
##詳細研究實際結果,直到你明白了它為何為 True 或 False。
##建立至少 10 個測試,且其中結果分别為 True 和 False 的測試都至少有 5 個。
number=5
print("Is number==5 ? I predict True." + "In fact, it is " + str(number == 5))
print("Is number!=5 ? I predict False." + "In fact, it is " + str(number != 5))
print("Is number<9 ? I predict True." + "In fact, it is " + str(number < 9))
print("Is number<=9 ? I predict True." + "In fact, it is " + str(number <= 9))
print("Is number<3 ? I predict False." + "In fact, it is " + str(number < 3))
print("Is number<=3 ? I predict False." + "In fact, it is " + str(number <= 3))
print("Is number>3 ? I predict True." + "In fact, it is " + str(number > 3))
print("Is number>=3 ? I predict True." + "In fact, it is " + str(number >= 3))
print("Is number>9 ? I predict False." + "In fact, it is " + str(number > 9))
print("Is number>=9 ? I predict False." + "In fact, it is " + str(number >= 9))

#5-2 更多的條件測試:你并非隻能建立 10 個測試。如果你想嘗試做更多的比較,可再編寫一些測試,并将它們加入到 conditional_tests.py 中。對于下面列出的各種測試,至少編寫一個結果為 True 和 False 的測試。
string_0='test'
string_1='Test'

## 檢查兩個字元串相等和不等。
print(string_0 == string_1)
print(string_0 != string_1)

## 使用函數 lower()的測試。
print(string_0 == (string_1.lower()))
print(string_0 != (string_1.lower()))

## 檢查兩個數字相等、不等、大于、小于、大于等于和小于等于。
number_0=3
number_1=6
print(number_0 == number_1)
print(number_0 != number_1)
print(number_0 > number_1)
print(number_0 < number_1)
print(number_0 >= number_1)
print(number_0 <= number_1)

## 使用關鍵字 and 和 or 的測試。
print((number_0 > 5) and (number_1 > 5))
print((number_0 > 5) and (number_1 < 5))
print((number_0 > 5) or (number_1 > 5))
print((number_0 > 5) or (number_1 < 5))

## 測試特定的值是否包含在清單中。
foods=['milk','orange']
food_0 = 'orange'
if food_0 in foods:
    print("Yes!")
else:
    print("No!")

## 測試特定的值是否未包含在清單中。
food_1 = 'meat'
if food_1 not in foods:
    print("Yes!")
else:
    print("No!")
           
  1. if語句

voting.py

  • 簡單的if語句
age=19
if age>=18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
           
  • if-else語句

經常需要在條件測試通過了時執行一個操作,并在沒有通過時執行另一個操作

#age=19
age=17
if age>=18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
#if-else語句
else:
    print("Sorry,you are too young to vote.")
    print("Please register to vote as soon as you turn 18!")
           
  • if-elif-else語句
limit_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.") """

if age < 4:
    price=0
elif age < 18:
    price=5
else:
    price=10
print("Your admission cost is $"+str(price)+".")
           
  • 使用多個elif代碼塊
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif limit_age<65:
    price = 10
else:
    price =5
print("Your admission cost is $" + str(price) + ".")
           
  • 省略else代碼塊

Python并不要求if-elif結構後面必須有else代碼塊

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

else是一條包羅萬象的語句,隻要不滿足任何if或elif中的條件測試,其中的代碼就會執行,這可能會引入無效甚至惡意的資料。

如果知道最終要測試的條件,應考慮使用一個elif代碼塊來代替else代碼塊。這樣,你就可以肯定,僅當滿足相應的條件時,你的代碼才會執行。

  • 測試多個條件
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!")
           

如果隻想執行一個代碼塊,就使用if-elif-else結構;

如果要運作多個代碼塊,就使用一系列獨立的if語句。

練習

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

if alien_color=='yellow':
    print("Congratulations, you gains 5 points!")
           
#5-4 外星人顔色#2:像練習 5-3 那樣設定外星人的顔色,并編寫一個 if-else 結構。
##如果外星人是綠色的,就列印一條消息,指出玩家因射殺該外星人獲得了5個點。
##如果外星人不是綠色的,就列印一條消息,指出玩家獲得了 10 個點。
##編寫這個程式的兩個版本,在一個版本中執行 if 代碼塊,而在另一個版本中執行 else 代碼塊。
alien_color = 'green'
#alien_color='yellow'
if alien_color=='green':
    print("Congratulations, you gains 5 points for shooting green aliens!")
else:
    print("Congratulations, you gains 10 points!")

#5-5 外星人顔色#3:将練習 5-4 中的 if-else 結構改為 if-elif-else 結構。
##如果外星人是綠色的,就列印一條消息,指出玩家獲得了 5 個點。
## 如果外星人是黃色的,就列印一條消息,指出玩家獲得了 10 個點。
## 如果外星人是紅色的,就列印一條消息,指出玩家獲得了 15 個點。
## 編寫這個程式的三個版本,它們分别在外星人為綠色、黃色和紅色時列印一條消息。
alien_color = 'green'
#alien_color='yellow'
#alien_color='red'
if alien_color=='green':
    print("Congratulations, you gains 5 points for shooting green aliens!")
elif alien_color=='yellow':
    print("Congratulations, you gains 10 points for shooting yellow aliens!")
elif alien_color=='red':
    print("Congratulations, you gains 15 ponts for shooting red aliens!")
           
#5-6 人生的不同階段:設定變量 age 的值,再編寫一個 if-elif-else 結構,根據 age的值判斷處于人生的哪個階段。
## 如果一個人的年齡小于 2 歲,就列印一條消息,指出他是嬰兒。
## 如果一個人的年齡為 2(含)~4 歲,就列印一條消息,指出他正蹒跚學步。
## 如果一個人的年齡為 4(含)~13 歲,就列印一條消息,指出他是兒童。
## 如果一個人的年齡為 13(含)~20 歲,就列印一條消息,指出他是青少年。
## 如果一個人的年齡為 20(含)~65 歲,就列印一條消息,指出他是成年人。
## 如果一個人的年齡超過 65(含)歲,就列印一條消息,指出他是老年人。
age=12
if age<2:
    print("You're still a baby!")
elif age<4:
    print("You're a toddler!")
elif age<13:
    print("You're a child!")
elif age<20:
    print("You're a teenager!")
elif age<65:
    print("You're an adult!")
elif age>=65:
    print("You're an old man!")
           
#5-7 喜歡的水果:建立一個清單,其中包含你喜歡的水果,再編寫一系列獨立的 if語句,檢查清單中是否包含特定的水果。
## 将該清單命名為 favorite_fruits,并在其中包含三種水果。
## 編寫 5 條 if 語句,每條都檢查某種水果是否包含在清單中,如果包含在清單中,就列印一條消息,如“You really like bananas!”。
fruits=['apple','orange','banana','strawberry','grape']
favorite_fruits=['banana','strawberry','grape']
if 'apple' in favorite_fruits:
    print("You really like apples!")
if 'orange' in favorite_fruits:
    print("You really like oranges!")
if 'banana' in favorite_fruits:
    print("You really like bananas!")
if 'strawberry' in favorite_fruits:
    print("You really like strawberries!")
if 'grape' in favorite_fruits:
    print("You really like grapes!")
           
  1. 使用if語句處理清單

pizzas.py

  • 檢查特殊元素
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!")
           
  • 确定清單不是空的
requested_toppings=[]
if requested_toppings:
    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?")
           

在if語句中将清單名用在條件表達式中時,Python将在清單至少包含一個元素時傳回True,并在清單為空時傳回False。

  • 使用多個清單
available_toppings=['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings=['mushrooms','french fries','extra cheese']
for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print("Adding "+requested_topping+".")
    else:
        print("Sorry,we don't have "+requested_topping+".")
print("\nFinished 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”。
user_names=['admin','jade','marry','john','doris','coral']
for user_name in user_names:
    if user_name=='admin':
        print("Hello admin, would you like to see a status report?")
    else:
        print("Hello "+user_name+" , thank you for logging in again.")
           
#5-9 處理沒有使用者的情形:在為完成練習 5-8 編寫的程式中,添加一條 if 語句,檢查使用者名清單是否為空。
## 如果為空,就列印消息“We need to find some users!”。
## 删除清單中的所有使用者名,确定将列印正确的消息。
user_names = []
if user_names:
    for user_name in user_names:
        if user_name == 'admin':
            print("Hello admin, would you like to see a status report?")
        else:
            print("Hello " + user_name + " , thank you for logging in again.")
else:
    print("We need to find some users!")
           
#5-10 檢查使用者名:按下面的說明編寫一個程式,模拟網站確定每位使用者的使用者名都獨一無二的方式。
## 建立一個至少包含 5 個使用者名的清單,并将其命名為 current_users。
## 再建立一個包含 5 個使用者名的清單,将其命名為 new_users,并確定其中有一兩個使用者名也包含在清單 current_users 中。
## 周遊清單 new_users,對于其中的每個使用者名,都檢查它是否已被使用。如果是這樣,就列印一條消息,指出需要輸入别的使用者名;否則,列印一條消息,指出這個使用者名未被使用。
## 確定比較時不區分大消息;換句話說,如果使用者名'John'已被使用,應拒絕使用者名'JOHN'。
current_users = ['jade', 'marry', 'john', 'doris', 'coral']
new_users = ['jack', 'marry', 'peter', 'doris', 'nick']
for user in new_users:
    if user in current_users:
        print(user.title()+" and "+user.upper()+" are already in use.Please enter another user name.")
    else:
        print(user.title()+" is not in use.")
           
# 5-11 序數:序數表示位置,如 1st 和 2nd。大多數序數都以 th 結尾,隻有 1、2 和 3例外。
## 在一個清單中存儲數字 1~9。
## 周遊這個清單。
## 在循環中使用一個 if-elif-else 結構,以列印每個數字對應的序數。輸出内容應為 1st、2nd、3rd、4th、5th、6th、7th、8th 和 9th,但每個序數都獨占一行。
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
    if number==1:
        print(str(number)+"st")
    elif number==2:
        print(str(number)+"nd")
    elif number==3:
        print(str(number)+"rd")
    else:
        print(str(number) + "th")
print("All output completed!")
           
  1. 設定if語句的格式

在諸如==、>=和<=等比較運算符兩邊各添加一個空格,例如,if age < 4:要比if age<4:好。

這樣的空格不會影響Python對代碼的解讀,而隻是讓代碼閱讀起來更容易。