If語句-python基礎篇六
阿新 • • 發佈:2021-09-06
IF語句
每條if 語句的核心都是一個值為True 或False 的表示式,這種表示式被稱為條件測試 條 。Python根據條件測試的值為True 還是False 來決定是否執行if 語句中的程式碼。如果 條件測試的值為True ,Python就執行緊跟在if 語句後面的程式碼;如果為False ,Python就忽略這些程式碼。
一、簡短的示例cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw': print(car.upper()) #以全大寫的方式列印它else: print(car.title()) #以首字母大寫的方式列印它 ''' Audi BMW Subaru Toyota '''
二、if-elif-else 結構
''' 4歲以下免費; 4~18歲收費5美元; 18歲(含)以上收費10美元。 ''' 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. #更簡單的寫法 age = 12 if age < 4: price = 0 elif age < 18: price = 5 else: price = 10 print("Your admission cost is $" + str(price) + ".") #替換寫法
三、使用使 if 語句處理列表
通過結合使用if 語句和列表,可完成一些有趣的任務:對列表中特定的值做特殊處理;高效地管理不斷變化的情形,如餐館是否還有特定的食材;證明程式碼在各種情形下都將按預期那樣執行。
例如:比薩店在製作比薩時,每新增一種配料都列印一條訊息。通過建立一個列表,在其中包含顧客點的配料,並使用一個迴圈來指出新增到比薩中的配料,但是當中的辣椒沒有貨了要單獨輸出一個畢竟特殊的結果
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! '''
四、使用多個列表
下面的示例定義了兩個列表,其中第一個列表包含比薩店供應的配料,而第二個列表包含顧客點的配料。這次對於requested_toppings 中的每個元素,都檢查它是否是比薩店供應的配料,再決定是否在比薩中新增它: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!") ''' Adding mushrooms. Sorry, we don't have french fries. Adding extra cheese. Finished making your pizza! '''