在 Python 中使用 if not 條件
    
    
            Najwa Riyaz
    2023年10月10日
    
    Python
    Python Condition
    
 
if 語句與 not 邏輯運算子結合以評估條件是否未發生。這篇文章解釋瞭如何在 Python 中使用 if not 條件。
這是一個演示這種情況的程式碼塊。
if not a_condition:
    block_of_code_to_execute_if_condition_is_false
在上述情況下,如果 a_condition 的結果為 False,程式碼 block_of_code_to_execute_if_condition_is_false 將成功執行。
Python 中的真假值
在開始之前,讓我們瞭解一下 Python 中的等價值在以下情況下是 False:
- 數字零值,例如 0、0L、0.0
- 空序列,例如:
- 空列表 []
- 空字典 {}
- 空字串''
- 空元組
- 空集
- None物件
 
Python 中 if not 條件的示例
以下是幾個示例,可幫助你瞭解如何在 Python 中使用 if not。
Boolean 值的使用
if not False:
    print("not of False is True.")
if not True:
    print("not of True is False.")
輸出:
not of False is True.
numeric 值的使用
例如,0、0L、0.0 等值與值 False 相關聯。
if not 0:
    print("not of 0 is True.")
if not 1:
    print("not of 1 is False.")
輸出:
not of 0 is True.
列表值的用法
if not []:
    print("An empty list is false. Not of false =true")
if not [1, 2, 3]:
    print("A non-empty list is true. Not of true =false")
輸出:
An empty list is false. Not of false =true
Dictionary 值的使用
if not {}:
    print("An empty dictionary dict is false. Not of false =true")
if not {"vehicle": "Car", "wheels": "4", "year": 1998}:
    print("A non-empty dictionary dict is true. Not of true =false")
輸出:
An empty dictionary dict is false. Not of false =true
字串值的的用法
if not "":
    print("An empty string is false. Not of false =true")
if not "a string here":
    print("A non-empty string is true. Not of true =false")
輸出:
An empty string is false. Not of false =true
None 值的使用:
if not None:
    print("None is false. Not of false =true")
輸出:
None is false. Not of false =true
set 值的用法:
dictvar = {}
print("The empty dict is of type", type(dictvar))
setvar = set(dictvar)
print("The empty set is of type", type(setvar))
if not setvar:
    print("An empty set is false. Not of false =true")
輸出:
   The empty dict is of type <class 'dict'>
   The empty set is of type <class 'set'>
   An empty dictionary dict is false. Not of false =true
使用元組值
空元組與值 False 相關聯。
if not ():
    print("1-An empty tuple is false. Not of false =true")
if not tuple():
    print("2-An empty tuple is false. Not of false =true")
輸出:
1-An empty tuple is false. Not of false =true
2-An empty tuple is false. Not of false =true
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe