常规的运算符不做过多解释,主要介绍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')
运行结果:
海象运算符和幂运算符还是很有拿来主义特色了
来源:CSDN
作者:Johan_Joe_King
链接:https://blog.csdn.net/Johan_Joe_King/article/details/104167587