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等),那么is,is not 和 ==,!= 是完全等价的。
对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
- 逻辑运算符
# 逻辑运算符
操作符 名称 示例
and 与 (3 > 2) and (3 < 5)
or 或 (1 > 3) or (9 < 2)
not 非 not (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