Python中的运算符
本文讲解Python中的运算符。
YouTube Video
Python中的运算符
Python有多种运算符,大致可以分为以下几类。我们将为每一类解释具有代表性的运算符。
算术运算符
算术运算符是用于对数字执行计算的运算符。
| 运算符 | 含义 | 示例 |
|---|---|---|
+ |
加法 | 3 + 2 → 5 |
- |
减法 | 3 - 2 → 1 |
* |
乘法 | 3 * 2 → 6 |
/ |
除法(始终为浮点数) | 3 / 2 → 1.5 |
// |
取整除法 | 3 // 2 → 1 |
% |
取余(模运算) | 3 % 2 → 1 |
** |
指数运算 | 3 ** 2 → 9 |
1a = 10
2b = 3
3
4print(f"{a} + {b} = {a + b}") # Addition
5print(f"{a} - {b} = {a - b}") # Subtraction
6print(f"{a} * {b} = {a * b}") # Multiplication
7print(f"{a} / {b} = {a / b}") # Division (float)
8print(f"6 / 3 = {6 / 3}") # Division (float)
9print(f"{a} // {b} = {a // b}") # Floor Division
10print(f"{a} % {b} = {a % b}") # Modulo (remainder)
11print(f"{a} ** {b} = {a ** b}") # Exponentiation- 除了四种基本的算术运算外,Python 还提供了除法(
/)、整除(//)、取模(%)和幂运算(**)的运算符。即使是对整数进行除法运算,结果也会返回浮点数。
赋值运算符
赋值运算符用于为变量赋值。
| 运算符 | 含义 | 示例 |
|---|---|---|
= |
赋值 | x = 5 |
+= |
加并赋值 | x += 2 → x = x + 2 |
-= |
减并赋值 | x -= 2 → x = x - 2 |
*= |
乘并赋值 | x *= 2 → x = x * 2 |
/= |
除并赋值 | x /= 2 → x = x / 2 |
//= |
取整除法 | x //= 2 → x = x // 2 |
%= |
求余并赋值 | x %= 2 → x = x % 2 |
**= |
幂并赋值 | x **= 2 → x = x ** 2 |
&= |
使用 AND 赋值 | x &= 0b1010 → x = x & 0b1010 |
|= |
使用 OR 赋值 | x | = 0b0011→x = x | 0b0011 |
^= |
使用 XOR 赋值 | x ^= 0b0101 → x = x ^ 0b0101 |
<<= |
左移后赋值 | x <<= 2 → x = x << 2 |
>>= |
右移后赋值 | x >>= 1 → x = x >> 1 |
:= |
赋值表达式(海象运算符) | if (n := len(data)) > 10: → 在判断条件时赋值给 n |
1x = 5 # x = 5
2
3x += 3 # x = x + 3
4x -= 2 # x = x - 2
5x *= 4 # x = x * 4
6x /= 3 # x = x / 3
7x //= 2 # x = x // 2
8x %= 5 # x = x % 5
9x **= 3 # x = x ** 3
10
11x = 0b1100 # x = 0b1100 (12)
12
13x &= 0b1010 # x = x & 0b1010
14x |= 0b0011 # x = x | 0b0011
15x ^= 0b0101 # x = x ^ 0b0101
16x <<= 2 # x = x << 2
17x >>= 1 # x = x >> 1
18
19print(bin(x)) # Display in binary
20print(x) # Display in decimal
21
22# Walrus operator
23if (n := len("hello")) > 3:
24 print(f"Length is {n}")- 赋值运算符允许将标准赋值与各种运算符结合使用,以便将结果赋值。
- 海象运算符(
:=)是 Python 3.8 及更高版本中提供的赋值表达式。 - 标准赋值只能作为语句使用,而海象运算符可以在表达式内部进行赋值。
比较运算符
比较运算符比较值并返回 True 或 False。
| 运算符 | 含义 | 示例 |
|---|---|---|
== |
等于 | 3 == 3 → True |
!= |
不等于 | 3 != 4 → True |
> |
大于 | 5 > 2 |
< |
小于 | 5 < 2 |
>= |
大于等于 | 5 >= 5 |
<= |
小于等于 | 3 <= 4 |
1a = 10
2b = 20
3
4# Equal to (==)
5print(f"{a} == {b} -> {a == b}") # False: a and b are not equal
6print(f"3 == 3.0 -> {3 == 3.0}") # True: int and float with the same value are equal
7print(f"3 == '3' -> {3 == '3'}") # False: different types (int vs str)
8print(f"True == 1 -> {True == 1}") # True: True is equivalent to 1
9print(f"False == 0 -> {False == 0}") # True: False is equivalent to 0
10print(f"None == 0 -> {None == 0}") # False: None is not equal to 0
11
12# Not equal to (!=)
13print(f"{a} != {b} -> {a != b}") # True: a and b are not equal
14
15# Greater than (>)
16print(f"{b} > {a} -> {b > a}") # True: 20 > 10
17
18# Less than (<)
19print(f"{a} < {b} -> {a < b}") # True: 10 < 20
20
21# Greater than or equal to (>=)
22print(f"{a} >= 10 -> {a >= 10}") # True: a is greater than or equal to 10
23
24# Less than or equal to (<=)
25print(f"{a} <= 10 -> {a <= 10}") # True: a is less than or equal to 10- 比较运算符比较两个值的大小或相等性,并返回
True或False作为结果。 - 在 Python 中,比较不同数据类型时应当小心。某些类型之间可以比较,但结果可能不直观。
逻辑运算符
逻辑运算符用于组合逻辑表达式。
| 运算符 | 含义 | 示例 |
|---|---|---|
and |
两者都为 True 时返回 True | True and False → False |
or |
任一为 True 时返回 True | True or False → True |
not |
取布尔值的反 | not True → False |
1x = 10
2print(x > 5 and x < 20) # True
3print(x < 5 or x > 20) # False
4print(not x == 10) # Falseand是逻辑运算符,只有左右两侧条件都为True时才返回True。or是逻辑运算符,只要左右两侧有一个条件为True,就返回True。not是逻辑运算符,用于取反条件的真假值。如果为真,则变为假;如果为假,则变为真。
逻辑运算符的优先级
运算符具有优先级。这是决定表达式中哪个运算符先被计算的规则。逻辑运算符的计算顺序是:not、and,然后是or。
1result = True or False and False
2print(result) # True
3
4result = (True or False) and False
5print(result) # Falseたとえば、
在第一个例子中,and会先被计算,因此False and False变为False,结果True or False变为True。你也可以用括号来改变计算顺序,正如第二个例子所示。
按位运算符
位运算符进行位级别的操作。
| 运算符 | 含义 | 示例 |
|---|---|---|
& |
按位与 | 5 & 3 → 1 |
| |
按位或 | 5 | 3→7 |
^ |
按位异或(XOR) | 5 ^ 3 → 6 |
~ |
按位取反 | ~5 → -6 |
<< |
左移 | 5 << 1 → 10 |
>> |
右移 | 5 >> 1 → 2 |
1# Sample code for bitwise operators
2
3# Define two integers
4a = 5 # Binary: 0101
5b = 3 # Binary: 0011
6
7# Bitwise AND
8result_and = a & b # Binary: 0001 -> Decimal: 1
9print(f"{a} & {b} = {result_and}")
10
11# Bitwise OR
12result_or = a | b # Binary: 0111 -> Decimal: 7
13print(f"{a} | {b} = {result_or}")
14
15# Bitwise XOR
16result_xor = a ^ b # Binary: 0110 -> Decimal: 6
17print(f"{a} ^ {b} = {result_xor}")
18
19# Bitwise NOT (inverting bits)
20result_not = ~a # Binary: -(0101 + 1) -> Decimal: -6
21print(f"~{a} = {result_not}")
22
23# Left shift
24shift_left = a << 1 # Binary: 1010 -> Decimal: 10
25print(f"{a} << 1 = {shift_left}")
26
27# Right shift
28shift_right = a >> 1 # Binary: 0010 -> Decimal: 2
29print(f"{a} >> 1 = {shift_right}")- 可以进行按位与、按位或、按位异或、按位取反运算,以及位移运算。你还可以与赋值运算符(如
&=)结合使用这些操作。
成员运算符
成员运算符用于检查集合(如列表和字典)。
1x = [1, 2, 3]
2y = 2
3z = 4
4
5print("y in x : ", y in x) # Result is True
6print("z in x : ", z in x) # Result is False
7
8print("y not in x : ", y not in x) # Result is False
9print("z not in x : ", z not in x) # Result is True
10
11text = "hello world"
12print("'world' in 'hello world' : ", "world" in text) # True
13print("'python' not in 'hello world' : ", "python" not in text) # Truein运算符用于判断指定的值是否包含在某个序列(如列表或字符串)或集合(如字典)中。not in运算符用于判断指定的值是否未包含在某个序列或集合中。
身份运算符
同一性运算符检查对象的同一性。
1x = [1, 2, 3]
2y = x
3z = x.copy()
4
5print("x is y : ", x is y) # Result is True
6print("x is z : ", x is z) # Result is False
7
8print("x is not y : ", x is not y) # Result is False
9print("x is not z : ", x is not z) # Result is True
10
11print("x == y : ", x == y) # Result is True
12print("x == z : ", x == z) # Result is Trueis运算符用于判断两个对象是否为同一个对象(即引用是否指向同一内存地址)。is not运算符用于判断两个对象是否为不同的对象。- 例如,
x is y与x == y不同,前者判断的是对象标识,而不是值是否相等。
类型检查
在 Python 中,可以使用isinstance()函数来检查一个值是否属于特定类型。你也可以使用type()函数来检查变量的确切类型。虽然这些不是运算符,但它们是进行类型检查的基本机制。
1x = 10
2print(isinstance(x, int)) # True
3
4y = "hello"
5print(isinstance(y, str)) # True
6
7z = [1, 2, 3]
8print(isinstance(z, list)) # True
9
10print(type(10)) # <class 'int'>
11print(type("hello")) # <class 'str'>
12
13print("isinstance(3, int) : ", isinstance(3, int)) # True
14print("type(3) is int : ", type(3) is int) # True
15print("type(True) is bool : ", type(True) is bool) # Trueisinstance()是一个用于判断对象是否为指定类或其子类的函数。type()是一个返回对象确切类型(类)的函数。它通常用于需要进行严格类型比较的时候。isinstance()会考虑继承关系,而type()只检查精确匹配。
总结
使用每个运算符时,需要根据其目的和类型适当选择。由于 Python 是一种动态类型语言,操作的结果可能会因所计算的值的类型而有所不同。
您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。