Day2-3运算符

it2024-04-11  52

运算符

前面我们所说进行数据类型转换的原因是不同类型的数据,它们的运算方式不同,那么下面我们来介绍数据之间运算所用的符号。

算数运算符

算数运算符主要就是我们数学上常用的一些符号,有加号+,减号-,乘号*,除号/,整除//,取余(取模)%,幂运算**

a = 5 b = 3 print(a+b) # 8 print(a-b) # 2 print(a*b) # 15 print(a/b) # 1.66666667 c = 6 d = 3 print(c/d) # 2.0 # python3中,两个整数相除,得到的结果会是一个浮点数 print(a//b)# 1 //表示取整数部分,向下取整 print(-5//2)# -3 print(a%b) # 2 %表示取余数部分 print(a**b)#125 表示5的3次方 x = 16 print(16**(1/2)) # 4.0

( ) 里的内容代表运算优先级

不同类型的数字在进行混合运算时,整数将会转换成浮点数进行。

print(5**2/5) # 5.0

算数运算符在字符串里的使用

# 使用加号用来拼接两个字符串 print('hello'+'world') # helloworld # 使用乘号用来重复字符串 print('hello'*5) # hellohellohellohellohello

在python中,字符串和数字之间不能使用加号连接

赋值运算符

赋值运算符就是=,但是不同于数学中的等号,计算机编程的=是将等号右边的值赋给等号左边,等号的左边一定不能是常量或者表达式

1 = b # 报错 b = 1 print(b) x = 1 x = x+1 # 先把1赋给x,然后x+1再赋给x,x现在的值为2 print(x)# 2 # 复合赋值运算符 y = 1 y +=1 # 和上述等价,表示先把1赋给y,然后y+1再赋给y,y现在的值为2 print(y) # 2 y -=1 print(y)# 1 y *=2 print(y)# 2 y /=1 print(y) # 2.0 y **=3 print(y)# 8.0 y //=3 print(y) #2.0 y %=2 print(y) # 0.0

赋值运算符的特殊场景

# 等号连接的变量可以传递赋值 a = b = c = d = 'hello' print(a,b,c,d) m,n = 3,5 # 拆包 print(m,n) x = 'hello','good','yes' print(x) # 拆包时,变量的个数和值的个数不一致时,会报错。 y,z = 1,2,3,4,5 o,p,q = 1,2 # *表示可变长度 o,*p,q = 1,2,3,4,5 print(o,p,q) # 1 [2, 3, 4] 5

比较运算符

比较运算符有大于>,小于<,大于等于>=,小于等于<=,不等于!=,等等==

print(2>1) # True print(4>9) # False print(5!=6) # True print(6==6) # True

比较运算符在字符串里的应用

字符串之间使用比较运算符,会根据各个字符的编码值逐一比较。ASCII码表。

print('a'>'b') # False print('abc'>'b') # False print('a'==6) # False print('a'!=6)# True

数字和字符串作==运算时结果为False,作!=运算时结果为True,其余运算会报错。

逻辑运算符

逻辑与and,逻辑或or,逻辑非not

print(2>1 and 3>4) # False print(2>1 or 3>4) # True print(not(2<4)) # False

逻辑运算符的短路

# 逻辑与运算的短路问题 4>3 and print('hello') # hello 4<3 and print('hello') # 没有结果 # 逻辑或运算的短路问题 4>3 or print('hello') # 没有结果 4<3 or print('hello') # hello

使用逻辑运算符得到的结果一定是布尔值吗,不一定!

逻辑运算符可以做取值。

# 逻辑与and运算中,会取第一个为False的值 print('hello' and [] and 'kdy') # [] # 如果所有的值均为True,那么取最后一个值 print('hello' and 'kdy' and 'daizi') # daizi # 逻辑或or运算中,会取第一个值为True的值 print('' or '家家' or 'hello') # 家家 # 当所有的值都是False,那么会取最后一个值 print('' or [] or {}) # {}

位运算符

将数字转化成二进制进行运算。

按位与& :同为1则为1,否则为0

按位或|:有1为1,没有1则为0

按位异或^:相同为0,不相同为1

按位左移<<:向左移几位,就在后面补几个0

按位右移>>:向右移几位,末尾就去掉几位数

a = 23 b = 15 print(bin(a)) # 0b10111 print(bin(b)) # 0b1111 print(a & b) # 0b111→7 print(a | b) # 0b11111→31 print(a ^ b) # 0b11000→24 x = 3 # 0b11 print(x<<3) # 0b11000→24 y = 13 # 0b1101 print(y>>2) # 0b11→3

十进制的数x,左移n位后为x×2的n次方,例如上面3左移3位后得24,3×2的三次方为24。 十进制的数x,右移n位后为x/2的n次方,例如上述13右移2位后得3,13/2的2次方为3。

练习

使用位运算,获取到十六进制颜色 0xF0384E 的RGB值,以十进制形式打印输出。

color = 0xF0384E red = color >> 16 print(red) green = color >> 8 & 0xFF print(green) blue = color & 0xFF print(blue)
最新回复(0)