Python 和關鍵詞



Python 的 and 關鍵詞是邏輯運算子之一。當兩個條件都為真時,結果為 True。它區分大小寫。當我們提供一個運算元時,它將導致 SyntaxError

and 關鍵詞可以用於條件語句迴圈函式中來檢查條件是 True 還是 False。它不能直接用於兩個數值之間,因為它會將兩個值都視為 True 值。

用法

以下是 Python and 關鍵詞的用法:

condition1 and condition2

這裡,condition1 和 condition2 可以是任何數值條件。

讓我們假設 A 和 B 是運算元,當 A 和 B 都為 True 時,結果為 True。如果任何一個運算元,A 或 B 為 False,結果為 False。以下是 and 關鍵詞的真值表:

A B A and B
True True True
True False False
False True False
False False False

示例

這是一個 Python and 關鍵詞的基本示例:

condition1=True
condition2=True
result_1=condition1 and condition2
print("The Result Of ",condition1,"And",condition2,":",result_1)
operand3=1
operand4=0
result_2=operand3 and operand4
print("The Result Of ",operand3,"And",operand4,":",result_2)

輸出

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

The Result Of  True And True : True
The Result Of  1 And 0 : 0

在 if-else 語句中使用 and 關鍵詞

and 關鍵詞可以用於 if-else 塊中來檢查條件結果是否為 True。如果兩個給定條件的結果都為 True,則執行 if 塊,否則執行 else 塊:

示例

讓我們透過以下示例來了解在 if-else 中使用 and 關鍵詞:

var1=54
var2=24
var3=12
if var1 > var2 and var1 < var3:
    print("Both The Conditions Are True")
else:
    print("One Of the Condition is True")

輸出

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

One Of the Condition is True

在迴圈中使用 and 關鍵詞

and 關鍵詞也用於迴圈中來檢查給定的條件語句,如果條件結果為 True,則執行該塊。

示例

在下面的示例中,我們在 while 迴圈中使用 and 關鍵詞:

list1=[]
x=2
while x<25 and True:
    if x%2==0:
        list1.append(x)
    x=x+1
print("We have appended the list1 with the even number below 25 :",list1)

輸出

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

We have appended the list1 with the even number below 25 : [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]

在函式中使用 and 關鍵詞

and關鍵字也用於函式中。如果給定的條件滿足,則返回True,否則返回False

示例

這是一個在函式中使用and關鍵字的示例:

def num(x):
    if x>5 and x<100:
        return True
    else:
        return False
		
var1=57
result_1=num(var1)
print(var1,"is between",5,"and",100,"True/False :",result_1)  
var2=600
result_2=num(var2)
print(var2,"is between",5,"and",100,"True/False :",result_2)

輸出

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

57 is between 5 and 100 True/False : True
600 is between 5 and 100 True/False : False

在數值中使用and關鍵字

我們不能使用數值作為and關鍵字的運算元。它會將兩個運算元都視為True,並返回第二個運算元。如果任何一個運算元為,則結果為

示例

這是一個在數值之間使用and關鍵字的示例:

var1=60
var2=100
result_1= var1 and var2
print("The Result of Two numeric values",var1,"and",var2,":",result_1)
var3=0
var4=18
result_2= var3 and var4
print("The Result of Two numeric values",var3,"and",var4,":",result_2)

輸出

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

The Result of Two numeric values 60 and 100 : 100
The Result of Two numeric values 0 and 18 : 0
python_keywords.htm
廣告