常規的運算符不做過多解釋,主要介紹Python自己的幾個特色運算符:
# - Tutorial 6
# - 2020-2-4
# - Johan
# - 題目:
# 1、算術運算符:** //
# 2、賦值運算符:**= //= :=
# 3、邏輯運算符:and or not
# 4、成員運算符:in not in
# 5、身份運算符:is is not
# **,冪運算,a**b等於求a的b次冪
print("3**3=%d" % 3 ** 3)
# **=,帶賦值的冪運算
n1 = 2
n1 **= 3
print("2**3=%d" % n1)
# //,整除運算,向下取整數數
print("17//5=%d" % (17//5))
# //=,帶賦值的整除運算
n2 = 21
n2 //= 4
print("21//4=%d" % n2)
# Python 3.8以後出現的海象運算符:=,用於在表達式中賦值,簡化代碼
# 原代碼
n = len('hello python')
if n > 10:
print('Got here. n=%d' % n)
# 改進後
if n := len('hello python'):
print('Got here. n=%d' % n)
# and,與運算
if (6 % 2 == 0) and (6 % 3 == 0):
print('6是2和3的倍數')
# or,或運算
if (4 % 3 == 0) or (7 % 3 == 0):
print('3是4的因數或是7的因數')
else:
print('3既不是4的因數也不是7的因數')
# not,非運算
if not 9 % 5 == 0:
print('9不能整除5')
# in,not in,查看元素是否在序列中
array = [1, 2, 3, 4, 5, 6]
if 3 in array:
print('3在序列中')
if 99 not in array:
print('99不在序列中')
# is,is not,用於判斷標識符是否引用同一個對象,==用於判斷值是否相同
c1 = 99
c2 = 99
c3 = 100
if c1 is c2:
print('c1 is c2')
if c1 is not c3:
print('c1 is not c3')
運行結果:
海象運算符和冪運算符還是很有拿來主義特色了