在本教程中,我們將討論如何在 Python 程序中使用不同的關係運算符。
關係運算符也稱為比較運算符,其主要功能是根據操作數的值返回真或假。
以下是關係運算符-
- <
- ==
- !=
- <=
讓我們從第一個開始-
1.大於或小於(>,
下面給出的程序說明了它是如何實現的
# Initializing the value of a and b
a = 20
b = 10
# Calculating the sum of a and b
c = a + b
print ("The sum of a and b is ", c)
# Using relational operators
print (a > b)
print (a < b)
print (c < a)
print (c > b)
輸出:
The sum of a and b is 30
True
False
False
True
解釋-
是時候看看上面程序的解釋了-
- 在第一步中,我們已經初始化了變量 a 和 b 的值分別是 20 和 10。
- 在下一步中,我們計算了 a 和 b 的總和。
- 最後,我們打印了基於大於或小於評估的值。
- 如果 a 大於 b,則輸出為“真”,否則輸出為“假”,反之亦然。
- 在執行給定程序時,會顯示所需的輸出。
2.等於(==)
如果存儲在兩個變量中的值相同,則等於“==”運算符返回真值。
下面的程序說明了它的用法
# Initializing the value of a and b
a = 20
b = 10
d = 30
#calculating the sum of a and b
c = a + b
e = d - b
print ("The sum of a and b is ", c)
print ("The difference of d and b is ", e)
# Using relational operators
print (a > b)
print (a < b)
print (c == d)
print (e == a)
輸出:
The sum of a and b is 30
The difference of d and b is 20
True
False
True
True
解釋-
讓我們了解一下在上面的程序中發生了什麼-
- 在第一步中,我們已經初始化了變量 a 和 b 的值分別是 20 和 10。
- 下一步,我們計算了 a 和 b 的和以及 d 和 b 的差。
- 最後,我們打印了基於大於、小於和等於計算的值。
- 如果 c 等於 d,則輸出為“真”,否則輸出為“假”,反之亦然。
- 在執行給定程序時,會顯示所需的輸出。
3.不等於(!=)
不等於!如果存儲在兩個變量中的值不同,則“=”運算符返回真值。
考慮下面給出的程序-
# Initializing the value of a and b
a = 20
b = 10
d = 30
# Calculating the sum of a and b
c = a + b
e = d - b
print("The sum of a and b is ", c)
print("The difference of d and b is ", e)
# Using relational operators
print(a > b)
print(a != b)
print(c!=d)
print(e==a)
輸出:
The sum of a and b is 30
The difference of d and b is 20
True
True
False
True
解釋-
讓我們看一下上面程序的解釋-
- 在第一步中,我們已經初始化了變量 a 和 b 的值分別是 20 和 10。
- 下一步,我們計算了 a 和 b 的和以及 d 和 b 的差。
- 最後,我們打印了基於大於、小於、等於和不等於計算的值。
- 如果 a 不等於 b ,則輸出為“真”,否則輸出為“假”,反之亦然。
- 在執行給定程序時,會顯示所需的輸出。
最後,我們將討論最後一個大於等於或小於等於的關係運算符。
4.大於或小於等於(> =,< =)
如果兩個變量中的任何一個的值大於或等於第二個,則大於等於返回“真”。
“小於等於”的作用方式類似。
讓我們看看如何在 Python 程序中使用它,
# Initializing the value of a and b
a = 20
b = 10
d = 30
# Calculating the sum of a and b
c = a + b
e = d - b
print("The sum of a and b is ", c)
print("The difference of d and b is ", e)
# Using relational operators
print(a >= b)
print(a != b)
print(c <= d)
print(e == a)
輸出:
The sum of a and b is 30
The difference of d and b is 20
True
True
True
True
解釋-
下面給出的程序說明了它是如何實現的
- 在第一步中,我們已經初始化了變量 a 和 b 的值分別是 20 和 10。
- 下一步,我們計算了 a 和 b 的和以及 d 和 b 的差。
- 最後,我們打印了基於大於、小於、等於、不等於、大於等於和小於等於計算的值。
- 如果 a 大於或等於 b,則輸出為“真”,否則輸出為“假”,反之亦然。
- 在執行給定程序時,會顯示所需的輸出。
結論
在本教程中,我們學習了如何在 Python 程序中使用關係運算符。
原創文章,作者:BL7D8,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/130335.html