2020-12-4 Python学习第二天(运算符)

Python小白学习02天

  • 算数运算符
# 算数运算符
操作符	名称		示例
+1 + 1
-2 - 1
*3 * 4
/3 / 4
//	 	整除		3 // 4
%	 	取余		3 % 4
**2 ** 3

# e.g
print(2 + 4)  # 4
print(3 - 1)  # 2
print(2 * 2)  # 4
print(3 / 4)  # 0.75
print(3 // 4)  # 0
print(3 % 4)  # 3
print(2 ** 3)  # 8
  • 比较运算符
# 比较运算符
操作符	名称		示例
>		大于		2 > 1
>=		大于等于	2 >= 4
<		小于		1 < 2
<=		小于等于	5 <= 2
==		等于		3 == 4
!=		不等于	3 != 5

# e.g
print(2 > 1)  # True
print(2 >= 4)  # False
print(1 < 2)  # True
print(5 <= 2)  # False
print(3 == 4)  # False
print(3 != 5)  # True

# 
a = "hello"
b = "hello"
print(a is b, a == b)  # True True
print(a is not b, a != b)  # False False

a = ["hello"]
b = ["hello"]
print(a is b, a == b)  # False True
print(a is not b, a != b)  # True False

is, is not 对比的是两个变量的内存地址
==, != 对比的是两个变量的值
比较的两个变量,指向的都是地址不可变的类型(str等),那么isis not==,!= 是完全等价的。
对比的两个变量,指向的是地址可变的类型(listdicttuple等),则两者是有区别的。


  • 逻辑运算符
# 逻辑运算符
操作符	名称		示例
and(3 > 2) and (3 < 5)
or(1 > 3) or (9 < 2)
notnot (2 > 1)

# e.g
print((3 > 2) and (3 < 5))  # True
print((1 > 3) or (9 < 2))  # False
print(not (2 > 1))  # False
  • 位运算符
# 位运算符
操作符	名称			示例
~		按位取反		~4
&		按位与		4 & 5
|		按位或		4 | 5
^		按位异或		4 ^ 5
<<		左移			4 << 2
>>		右移			4 >> 2

# e.g
print(bin(4))  # 0b100
print(bin(5))  # 0b101
print(bin(~4), ~4)  # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)  # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1
  • 其他运算符
# 其他运算符
操作符	名称		示例
in		存在		'A' in ['A', 'B', 'C']
not in	不存在	'h' not in ['A', 'B', 'C']
is"hello" is "hello"
not is	不是		"hello" is not "hello"

# e.g
gorgeous_boy = ["吴彦祖", "梁朝伟", "彭于晏"]
if "吴彦祖" in gorgeous_boy:
	print("吴彦祖" + "是帅哥")
if "我" not in gorgeous_boy:
	print("我" + "不是帅哥") 
	
# 吴彦祖是帅哥
# 我不是帅哥

  • 三元运算符
# 三元运算符
x, y = 4, 5
if x < y:
    small = x
else:
    small = y

print(small)  # 4

# 变式
x, y = 4, 5
small = x if x < y else y

print(small)  # 4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值