在 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