1. 程式人生 > 其它 >Python基礎: if語句

Python基礎: if語句

技術標籤:Python

一個簡單的示例

先來一個入門案例,假設你有一個汽車列表,並想將所有的汽車名稱都打印出來,對於大多數汽車,都應該首字母大寫列印,但對於bmw,應該全部大寫列印:

cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

在這裡插入圖片描述

條件測試

每條if語句的核心都是一個值為False或者True的表示式,這種表示式被稱為條件測試,Python根據條件測試的值來判斷是否執行if語句中的程式碼:如果為True就執行,否則不執行.又稱為布林表示式,True和false稱為布林值.

檢測是否相等

使用雙等號 ==

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

foods = ['egg', 'MILK']
if (foods[0].upper() == "EGG"):
    print("True")
if (foods[1].lower() == "milk"):
    print("True")

在這裡插入圖片描述

檢測是否不相等

使用 !=

比較數字

age = 18
print(age == 18)
answer = 17
if answer != 42:
    print("False answer"
)

在這裡插入圖片描述
還可以使用<, <=, >, >= 來進行判斷

檢測多個條件

and 和 or 關鍵字

and相當於Java的&&

nums = [1, 2, 3]
print(nums[0] == 1 and nums[-1] == 3)

在這裡插入圖片描述

or相當於Java的||

nums = [1, 2, 3]
print(nums[0] == 1 or nums[1] == 3)

在這裡插入圖片描述

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

使用 in 關鍵字

nums = [1, 2, 3]
print(1 in nums)
print(0 in nums)

在這裡插入圖片描述

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

使用關鍵字 not in

nums = [1, 2, 3]
print(1 not in nums)
print(0 not in nums)

在這裡插入圖片描述

if語句

最簡單的if語句

最簡單的if語句只有一個測試和一個操作

age = 18
if age == 18:
    print("It's a perfect age!")

在這裡插入圖片描述

if-else語句

age = 17
if age >= 18:
    print("You are old enough to vote!")
else:
    print("Sorry, you are too young to vote!")

在這裡插入圖片描述

if-elif-else結構

在現實世界中,很多情況下都需要考慮超過2個以上的情形,例如,我們來看一個根據年齡收費的遊樂場:

  • 4歲以下免費
  • 4~18歲收費5美元
  • 18歲(含)以上收費10美元
age = 17
if age < 4:
    print("your admission is 0.")
elif age < 18:
    print("your admission is $5.")
else:
    print("your admission is $10.")

在這裡插入圖片描述

使用多個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) + ".")

在這裡插入圖片描述

省略else程式碼塊

Python並不要求if-elif結構後面必須有else語句,在有些情況下else語句很有用,但有時用elif來處理邏輯會更加清晰.

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

在這裡插入圖片描述

使用if語句來處理列表

通過結合if語句和列表,可以完成一些有趣的任務:對列表中特定的值做特殊處理;高校的管理不斷變化的情形,如餐館是否還有特定的食材;證明程式碼在各種情況下都將按照預期那樣進行.

檢查特殊元素

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

在這裡插入圖片描述
然而,如果比薩店的青椒用完了,該如何處理呢?為妥善處理這種情況,可在for迴圈中包含一條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!")

在這裡插入圖片描述

確定列表不是空的

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + ".")
    print("Are you sure you want a plain pizza!")
else:
    print("Are you sure you want a plain pizza?")

print("\nFinished making your pizza!")

在這裡插入圖片描述

使用多個列表

available_toppings = [1, 2, 3, 4, 5, 6]
requested_toppings = [1, 3, 4, 5, 7, 9]
for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print("Adding " + str(requested_topping) + ".")
    else:
        print("Sorry, we don't have " + str(requested_topping) + ".")

在這裡插入圖片描述