Python—运算符

欢迎关注微信公众号(医学生物信息学),医学生的生信笔记,记录学习过程。

算术运算符

在算术运算符中使用%求余,如果除数(第二个操作数)是负数,那么取得的结果也是一个负数。

print('加法:',1+1)
print('减法:',1-1)
print('乘法:',2*3)
print('除法:',10/2)
print('整除:',10//3)
print('取余:',10%3)
print('幂运算:',2**4) # 2*2*2*2

除数不能为0:

print(10/0) 

print(230//0)

赋值运算符

x=20 # 直接赋值,直接将20赋值给左侧的变量x
y=10
x=x+y # 将x+y的和赋值给x ,x的值为30
print(x)  # x的值是30

x+=y   # 40  相当于x=x+y
print(x)

x-=y # 相当于x=x-y
print(x) # 30

x*=y
print(x) # 300

x/=y
print(x) #30.0 发生了类型转换 x的数据类型为float类型
print(type(x)) # <class 'float'>

x%=2 # 相当于 x=x%2
print(x) # 0.0

z=3
y//=z  # 相当于y=y//z
print(y) # 3

y**=2 # 相当于 y=y**2
print(y)  # 9

# Python支持链式赋值
a=b=c=100 # 相当于执行 a=100 b=100  c=100
print(a,b,c)

# Python支持系列解包赋值
a,b=10,20  # 相当于执行了a=10  b=20
print(a,b)

#交换两个变量的值
a,b=b,a # 将b的值赋给a,将a的值赋给b
print(a,b)

比较运算符

print('98大于90吗?',98>90)
print('98小于90吗?',98<90)
print('98等于90吗?',98==90)
print('98不等于90吗?',98!=90)
print('98大于等于98吗?',98>=98)
print('98小于等于98吗?',98<=98)

逻辑运算符

print(True and True)
print(True and False)
print(False and False)
print(False and True)

print(8>7 and 6>5) # True
print(8>7 and 6<5)  # False
print(8<7 and 10/0) # False ,10/0并没有运算,当第一个表达式的结果为False,直接得结果,不会计算 and右侧的表达式了

print(True or True)
print(True or False)
print(False or False)  # False
print (False or True)

print(8>7 or 10/0) # True ,左侧的表达式结果为True时,or的右侧表达式根本不执行运算符

print( not True ) # False
print( not False) # True
print( not (8>7) ) # False

位运算符

位运算符:把数字看作二进制数来进行计算的。

print('按位与运算:',12&8)
print('按位或运算:',4|8)
print('按位异或运算符:',31^22)
print('按位取反:',~123)

print('左移位:',2<<2) # 8, 表示的是2向左移动两位   2*2*2
print('左移位:',2<<3) # 相当于 2* 2*2*2
print('右移位:',8>>2) # 8向右移动两位相当于 8//2 ,4//2
print('右移位:',-8>>2) # -2

运算符的优先级

参考资料

[1] https://www.bilibili.com/video/BV1wD4y1o7AS/?p=7&share_source=copy_web&vd_source=d40f0854606900163a564a59cfa3027c

[2] 零基础Python学习笔记 明日科技编著

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值