Python not 關鍵字



在 Python 中,not 關鍵字是邏輯運算子之一。如果給定的條件為 True,則結果為 False。如果給定的條件為 False,則結果為 True。它是一個 區分大小寫的關鍵字。

not 關鍵字操作僅對一個運算元執行。它可以用於 條件語句迴圈函式 中來檢查給定的條件。

語法

以下是 Python not 關鍵字的基本語法:

not condition

讓我們考慮 A 為條件。如果 ATrue,則它將返回 False。當 AFalse 時,它將返回 True。以下是 Python not 關鍵字真值表:

A not A
True False
False True

示例

以下是 Python not 關鍵字的基本示例:

var1=1
result_1=not var1
print("The Result of not operation on",var1,":",result_1)
var2=0
result_2=not var2
print("The Result of not operation on",var2,":",result_2)

輸出

以下是上述程式碼的輸出:

The Result of not operation on 1 : False
The Result of not operation on 0 : True

在 if 語句中使用 'not'

我們可以將 not 關鍵字與 if 語句一起使用。當條件為 False 時,不會執行程式碼的 if 塊,為了使程式碼可執行,我們需要將 False 條件變為 True,我們在條件前使用 not 運算子。

示例

在這裡,我們已將值賦給變數,它被視為 True 值,因此當我們在條件前放置 not 時,它會導致 False,因此執行 else 塊:

var1=45
if not var1:
    print("Hello")
else:
    print("Welcome to TutorialsPoint")

輸出

以下是上述程式碼的輸出:

Welcome to TutorialsPoint

在 while 迴圈中使用 'not'

not 可以與 while 迴圈一起使用。我們可以透過在 while 迴圈中使用 not 運算子,在指定條件未滿足時進行迭代。

示例

在以下示例中,我們在 while 迴圈中使用了 not

def prime_num(n):  
  i = 2  
    
  while not i > n:  
    for j in range(2, i//2):  
      if i%j == 0:  
        break  
    else: print(i,end=' ')  
    i += 1  
  
# Calling the function  
prime_num(10)  

輸出

以下是上述程式碼的輸出:

2 3 4 5 7
python_keywords.htm
廣告