如何在 Python 中使用 if 語句編寫條件分支

商業

用 Python 中的 if 語句解釋條件分支。

  • if 語句的基礎知識(if、elif、else)
  • 使用比較運算符等指定條件。
  • 通過編號、列表等指定條件。
  • 使用邏輯運算符(and、or、not)指定多個條件或否定
  • 新行和多行的條件表達式

還有一個三元運算符在一行中描述一個條件分支。請參閱以下文章。

if 語句的基礎知識(if、elif、else)

if語句的基本形式如下

if Conditional expression 1:
    `Processing to be performed if Expression 1 is True.`
elif Conditional expression 2:
    `Processing to be performed when expression 1 is false and expression 2 is true.`
elif Expression 3:
    `Process when expression 1 and 2 are false and expression 3 is true.`
...
else:
    `Processing when all conditionals are false.`

“elif”對應於C等語言中的“else if”,可以有任意數量的“elif”。

如果不需要假時只有一個條件表達式或處理,“elif”和“else”塊可以省略。

使用比較運算符等指定條件。

使用返回布爾類型(真、假)的操作(如比較運算符)指定條件。

Python比較運算符如下

操作員結果
x < y如果 x 小於 y,則為真
x <= y如果 x 小於或等於 y,則為真
x > y如果 x 大於 y,則為真
x >= y如果 x 大於或等於 y,則為真
x == y如果 x 和 y 值相等,則為 true
x != y如果 x 和 y 值不相等,則為 truex is y如果 x 和 y 是同一個對象,則為 truex is not y如果 x 和 y 不是同一個對象,則為 truex in y如果 x 包含在 y 中,則為真x not in y如果 x 不包含在 y 中,則為真

例子。為方便起見,它被定義為帶有 def 語句的函數。

def if_test(num):
    if num > 100:
        print('100 < num')
    elif num > 50:
        print('50 < num <= 100')
    elif num > 0:
        print('0 < num <= 50')
    elif num == 0:
        print('num == 0')
    else:
        print('num < 0')

if_test(1000)
# 100 < num

if_test(70)
# 50 < num <= 100

if_test(0)
# num == 0

if_test(-100)
# num < 0

以下內容可以用 Python 獨有的方式編寫。有關詳細信息,請參閱以下文章。
a < x < b

def if_test2(num):
    if 50 < num < 100:
        print('50 < num < 100')
    else:
        print('num <= 50 or num >= 100')

if_test2(70)
# 50 < num < 100

if_test2(0)
# num <= 50 or num >= 100
  • #ERROR!
  • !=

以上是數值對比;要比較對象身份,請使用以下命令

  • is
  • is not

例如,在比較整數和浮點數時,如果值相等,“==”返回 true,但“is”返回 false,因為它們是不同的對象。

i = 10
print(type(i))
# <class 'int'>

f = 10.0
print(type(f))
# <class 'float'>

print(i == f)
# True

print(i is f)
# False

也可以設置列表或字符串是否包含特定元素(字符)的條件。

  • in:包括
  • not in:不包括
def if_test_in(s):
    if 'a' in s:
        print('a is in string')
    else:
        print('a is NOT in string')

if_test_in('apple')
# a is in string

if_test_in('melon')
# a is NOT in string

通過編號、列表等指定條件。

if 語句的條件表達式可以是數字、列表或其他非 bool 類型的對象(true、false)。

if 10:
    print('True')
# True

if [0, 1, 2]:
    print('True')
# True

在 Python if 語句的條件表達式中,以下對像被認為是錯誤的。

表示零、空字符串、列表等的數字被認為是錯誤的;所有其他都被認為是真實的。

可以用 bool() 來檢查對像是如何判斷的。

print(bool(10))
# True

print(bool(0.0))
# False

print(bool([]))
# False

print(bool('False'))
# True

例如,這可用於在列表為空時簡單地編寫進程。

def if_test_list(l):
    if l:
        print('list is NOT empty')
    else:
        print('list is empty')

if_test_list([0, 1, 2])
# list is NOT empty

if_test_list([])
# list is empty

請注意,字符串 ‘False’ 也將為真,因為如上例所示,字符串中任何非空字符串都將為真。要將特定字符串(例如 ‘True’ 或 ‘False’ )轉換為 1,0,請使用 distutils.util 模塊中的 strtobool()。

使用邏輯運算符(and、or、not)指定多個條件或否定

邏輯運算符(and、or、not)可用於處理多個條件的邏輯合取、邏輯析取和否定。

操作員(結果(在 if 語句的條件表達式中)
x and y如果 x 和 y 都為真,則為真
x or y如果 x 或 y 為真,則為真
not x如果 x 為真,則為假,如果 x 為假,則為真
def if_test_and_not(num):
    if num >= 0 and not num % 2 == 0:
        print('num is positive odd')
    else:
        print('num is NOT positive odd')

if_test_and_not(5)
# num is positive odd

if_test_and_not(10)
# num is NOT positive odd

if_test_and_not(-10)
# num is NOT positive odd

實際上,”x and y” 和 “x or y” 不返回 True 或 False,而是返回 x 或 y。只要它們在 if 語句的條件表達式中使用,就不必擔心它們,因為它們的計算結果要么是 True 要么 False。有關詳細信息,請參閱以下文章。

可以多次使用和和或。

def if_test_and_not_or(num):
    if num >= 0 and not num % 2 == 0 or num == -10:
        print('num is positive odd or -10')
    else:
        print('num is NOT positive odd or -10')

if_test_and_not_or(5)
# num is positive odd or -10

if_test_and_not_or(10)
# num is NOT positive odd or -10

if_test_and_not_or(-10)
# num is positive odd or -10

新行和多行的條件表達式

當通過“and”或“or”連接多個條件表達式並使用它們並且每行變長時,有時需要將條件表達式打斷並將其寫入多行。

可以通過使用反斜杠或將整行括在括號中來進行換行。

def if_test_and_backslash(num):
    if num >= 0 \
       and not num % 2 == 0:
        print('num is positive odd')
    else:
        print('num is NOT positive odd')

if_test_and_backslash(5)
# num is positive odd

def if_test_and_brackets(num):
    if (num >= 0
        and not num % 2 == 0):
        print('num is positive odd')
    else:
        print('num is NOT positive odd')

if_test_and_brackets(5)
# num is positive odd

您可以使用反斜杠多次換行。同樣,您可以在括號內多次換行。沒有縮進限制。

請注意,這是一種可以在 Python 代碼中的任何地方使用的技術,而不僅僅是在 if 語句中。

Copied title and URL