Python 中的運(yùn)算符
什么是運(yùn)營(yíng)商?
在編程中,運(yùn)算符是用于執(zhí)行數(shù)字或邏輯運(yùn)算的字符。
Python 支持許多不同類型的運(yùn)算符。在本課中,我們將學(xué)習(xí)以下常用運(yùn)算符:
算術(shù)運(yùn)算符
比較運(yùn)算符
賦值運(yùn)算符(用于變量)
邏輯運(yùn)算符
成員資格測(cè)試運(yùn)算符(檢查給定值內(nèi)是否存在值)
算術(shù)運(yùn)算符
Python 支持所有用于執(zhí)行加法、減法、乘法、除法、求冪和求余的常用算術(shù)運(yùn)算符。
a = 10
b = 5
print(a + b) # 15 (= 10 + 5)
print(a - b) # 5 (= 10 - 5)
print(a/b) # 2 (= 10 : 5)
print(a*b) # 50 (= 10 x 5)
print(a%b) # 0 (10 : 5 d? 0)
print(a**b) # 100000 (= 10^5)
比較運(yùn)算符
比較運(yùn)算符用于比較值。例如:
a = 5
b = 10
# Ki?m tra a nh? h?n b
print(a < b) # True
# Ki?m tra a l?n h?n b
print(a > b) # False
# Ki?m tra a nh? h?n 5
print(a < 5) # False
# Ki?m tra a khác b
print(a != b) # True
print(a <> b) # True
# Ki?m tra a khác 5
print(a != 5) # False
# Ki?m tra a b?ng 5
print(a == 5) # True
# Ki?m tra a nh? h?n ho?c b?ng 5
print(a <= 5) # True
# Ki?m tra a l?n h?n ho?c b?ng 5
print(a >= 5) # True
上面你注意到我們使用兩個(gè)等號(hào)來(lái)比較相等性,?==
?而不僅僅是 1 個(gè)符號(hào)?=
。
賦值
賦值運(yùn)算符用于設(shè)置初始值或更改變量的值。我們?cè)谇懊娴氖纠薪?jīng)常使用的賦值運(yùn)算符之一是?=
.
a = 5
此外,我們還有一個(gè)運(yùn)算符?+=
?也用于賦值:
a = 5
b = 10
print(a) # 5
a += b # T??ng ???ng a = a + b
print(a) # 15
a += 3 # T??ng ???ng a = a + 3
print(a) # 18
同樣,我們還有運(yùn)算符?-=
,??*=
,?/=
?和?**=
:
a = 10
b = 5
a -= b # T??ng ???ng a = a - b
print(a) # 5 (= 10 - 5)
a *= b # T??ng ???ng a = a * b
print(a) # 25 (= 5 x 5)
a /= b # T??ng ???ng a = a / b
print(a) # 5 (= 25 : 5)
a **= b # T??ng ???ng a = a**b
print(a) # 3125 (= 5^5)
邏輯運(yùn)算符
用于執(zhí)行邏輯運(yùn)算的邏輯運(yùn)算符包括:
and
?用于執(zhí)行邏輯運(yùn)算的運(yùn)算?符?和運(yùn)算符?
or
?用于執(zhí)行邏輯運(yùn)算?或not
?用于執(zhí)行負(fù)邏輯?運(yùn)算的運(yùn)算符?
例如:
a = True
b = False
print(a and b) # False
print(a or b) # True
print(!a) # False
print(!b) # True
會(huì)員運(yùn)營(yíng)商
成員資格運(yùn)算符用于測(cè)試給定值內(nèi)是否存在值。這個(gè)給定值的數(shù)據(jù)類型通常有字符串(string)、列表(list)、元組…… Python有兩個(gè)隸屬運(yùn)算符?in
?and??not in
?(和)相反?in
。例如:
a = "Hello World!"
print("W" in a) # True
print("o" in a) # True
print("w" in a) # False
print("!" not in a) # False
文章鏈接:https://www.dianjilingqu.com/728475.html