Python 运算符深入指南:初学者到专业人士

Python 运算符深入指南:初学者到专业人士


发布日期: 2024-01-10 更新日期: 2024-01-10 编辑:xuzhiping 浏览次数: 350

标签:

摘要: 在本文中,我们深入介绍了需要了解的所有 Python 运算符,包括向您展示如何使用它们的代码示例。 作为三大编程语言之一,Python 通常是数据科学、Web 开发等领域的初学者和经验丰富的专业人士的首选。而当谈到 Python 编程时,了解如何使用 Py...

Python 运算符深入指南:初学者到专业人士

在本文中,我们深入介绍了需要了解的所有 Python 运算符,包括向您展示如何使用它们的代码示例。

作为三大编程语言之一,Python 通常是数据科学、Web 开发等领域的初学者和经验丰富的专业人士的首选。而当谈到 Python 编程时,了解如何使用 Python 运算符是一项必备技能。无论您是学习 Python 的新手,还是希望提高 Python 运算符技能的经验丰富的专业人士,本文都涵盖了从基本算术和比较运算符到复杂的按位运算符和海象运算符的所有内容!

什么是 Python 运算符?

什么是 Python 运算符

当谈到学习基本的 Python 概念时,Python 运算符是非常基础的。这些是对一个或多个操作数执行特定操作的特殊符号和关键字,使其成为编程中操作数据和在代码中做出决策的重要工具。

无论您是刚刚开始使用 Python,还是正在构建 Python 项目的经验丰富的开发人员,运算符都会出现在您创建的几乎每个 Python 程序中。这些操作的范围可以从基本算术到复杂的逻辑和数据操作。运算符是几乎所有编程语言(不仅仅是 Python)的基础,并且是所有软件的构建块。

Python 中的运算符还在优化和细化代码方面发挥着作用。例如,按位运算符可以在二进制级别提供高效的数据操作,这在性能至关重要时至关重要。本质上,运算符是连接人类逻辑与机器处理的语法。它们就像编程的语法,当组合在一起时,就可以在 Python 代码中表达复杂的操作和逻辑。现在让我们深入研究各种 Python 运算符,从常见的算术和比较运算符到专用运算符(如按位运算符和名字滑稽的海象运算符)!

从常见的算术和比较运算符到专用运算符

1.算术运算符

Python 算术运算符是执行数学运算的基本工具,包括用于加法、减法、乘法等的符号。 下次当启动 Python IDE 并编写需要使用数学的程序时,会发现算术运算符是不可或缺的。

加法(+)

加法运算符用于对两个值求和。当与数字一起使用时,执行算术加法。当与字符串一起使用时,它将其连接起来。

重要的一点:不能使用此运算符来组合(连接)不同数据类型的对象。例如,如果尝试连接字符串和整数,则会抛出 TypeError。这是 Python 初学者常犯的错误。事实上,加法运算符可能是您在学习Python 课程时将学习使用的第一个运算符,因为它对于所有技能水平来说都非常容易理解并且易于使用。

'''
Python Addition Operator Example
'''
x = 5
y = 3
print(x + y)  # Outputs: 8

# For strings
str1 = "Hello"
str2 = "World"
print(str1 + str2)  # Outputs: HelloWorld

减法(-)

此 Python 运算符从左侧的值中减去右侧的值,它主要用于涉及数字的算术运算。

'''
Python Subtraction Operator Example
'''
x = 8
y = 3
print(x - y)  # Outputs: 5

乘法(*

此 Python 运算符将两个操作数相乘。对于数字,它给出乘积,但是当与字符串和数字一起使用时,它会重复字符串一定次数。

'''
Python Multiplication Operator Example
'''
x = 7
y = 4
print(x * y)  # Outputs: 28

# For strings
str1 = "Hello"
print(str1 * 3)  #: HelloHelloHello

除法(/)

此 Python 运算符将左操作数除以右操作数,结果提供浮点除法。

'''
Python Division Operator Example
'''
x = 20
y = 4
print(x / y)  # Outputs: 5.0

Modulus(%)

Modulus(模量)作为较不寻常的算术运算符之一,如果是编程新手,可能会问 Python 中的 % 是什么。

Python 中的 % 是返回除法运算余数的一种方法。当想要找出余数(例如确定数字是偶数还是奇数)时,这特别有用。

'''
Python Modulus Operator Example
'''
x = 29
y = 4
print(x % y)  # Outputs: 1

求幂 ( **)

此 Python 指数运算符计算左操作数的右操作数次方。

'''
Python Exponentiation Operator Example
'''
x = 3
y = 4
print(x ** y)  # Outputs: 81

Floor Division (//)

对于编程新手来说,这是另一个比较不常见的算术运算符,但是 Python 中的 // 是什么?这与正常的除法有何不同?

Python 中的 // 是一种除法,它将结果向下舍入到最接近的整数,而忽略小数余数。因此,有时称为整数除法。

'''
Python Floor Division Operator Example
'''
x = 17
y = 4
print(x // y)  # Outputs: 4

2.比较运算符(关系运算符)

Python 比较运算符通常称为关系运算符,它们用于比较两个值,返回布尔值 True 或 False。 当需要通过 Python 的条件语句实现决策过程时,这些 Python 比较运算符至关重要,这反过来又允许我们的代码根据特定条件进行分支或循环。

等于 (==)

最常见的 Python 相等运算符,用于检查两个操作数的值是否相同。如果相等,则返回 True,否则返回 False。

重要提示:如果不熟悉比较,那么了解 Python equal 和 is 运算符之间的区别非常重要。 TL-DR:当需要检查值是否相等时,相等运算符是理想的选择,而 is 运算符用于检查对象本身是否相等。

'''
Python "Equal to" Operator Example
'''
x = 5
y = 5
z = 6
print(x == y)  # Outputs: True
print(x == z)  # Outputs: False

不等于 (!=)

此 Python 比较运算符检查不等式,这意味着如果操作数值不同,则返回 True。与其相反的相等运算符非常相似,它非常适合构建流控制结构(例如Python while 循环)以及条件语句。

'''
Python "Not equal to" Operator Example
'''
x = 5
y = 7
print(x != y)  # Outputs: True

小于 (<)

此 Python 运算符确定左侧的值是否小于右侧的值,如果是,则返回 True。

'''
Python "Less than" Operator Example
'''
x = 3
y = 5
print(x < y)  # Outputs: True

大于 (>)

此 Python 运算符检查左侧值是否大于右侧值,如果是,则返回 True。

'''
Python "Greater than" Operator Example
'''
x = 8
y = 5
print(x > y)  # Outputs: True

小于或等于 (<=)

该 python 运算符检查两个条件,即左操作数值是否小于或等于右操作数值,如果其中一个条件为 True,则返回 true。

'''
Python "Less than or equal to" Operator Example
'''
x = 7
y = 7
z = 8
print(x <= y)  # Outputs: True
print(x <= z)  # Outputs: True

大于或等于 (>=)

此 Python 运算符检查两个条件,即左操作数的值是否大于或等于右操作数,如果其中一个条件为 True,则返回 true。

'''
Python "Greater than or equal to" Operator Example
'''
x = 9
y = 6
z = 9
print(x >= y)  # Outputs: True
print(x >= z)  # Outputs: True

3.逻辑运算符(布尔运算符)

Python 逻辑运算符有时称为布尔运算符,它评估一个或多个条件的真实性或逻辑状态并返回一个布尔值。 这使得逻辑运算符对于从多个运算符构造复合条件并在代码中细化决策逻辑至关重要。

逻辑与(AND)

Python AND 运算符如果其两边的条件都为 true,则返回 True,并且它经常在条件语句中用于检查多个条件。

'''
Python Logical AND Operator Example
'''
x = True
y = False
print(x and y)  # Output: False

逻辑或(OR)

如果至少一个周围条件为 true,Python OR 运算符将返回 True。

'''
Python Logical OR Operator Example
'''
x = True
y = False
print(x or y)   # Output: True

逻辑非(not)

此 Python 运算符反转其前面条件的真值。例如,如果条件为 True,则 not 将使其变为 False。在所有 Python 逻辑运算符中,这对于布尔逻辑初学者来说可能是最令人困惑的。

'''
Python Logical NOT Operator Example
'''
x = True
print(not x)  # Output: False

4.按位运算符

Python 按位运算符直接处理数字的各个位,它们用于在二进制级别执行 AND、OR 和 XOR 等运算。 虽然 Python 按位运算符看起来有点深奥,但它们非常强大,并且经常用于需要对数据进行位级操作的领域,例如密码学、图形处理和高性能应用程序。如果对这些想法感兴趣,

按位与 (&)

此 Python 逻辑 AND 运算符在位级别工作,对整数的二进制表示形式执行按位运算,并返回结果。

'''
Python Bitwise AND Operator Example
'''
x = 12  # 1100 in binary
y = 10  # 1010 in binary
print(x & y)  # Output: 8 (which is 1000 in binary)

按位或 (|)

此 Python 逻辑 OR 运算符对整数的二进制数字执行按位运算,并返回结果。

'''
Python Bitwise OR Operator Example
'''
x = 12  # 1100 in binary
y = 10  # 1010 in binary
print(x | y)  # Output: 14 (which is 1110 in binary)

按位异或 (^)

Python ^ 运算符返回一个由 1(两个二进制数不同)和 0(相同)组成的数字。

'''
Python Bitwise XOR Operator Example
'''
x = 12  # 1100 in binary
y = 10  # 1010 in binary
print(x ^ y)  # Output: 6 (which is 0110 in binary)

按位非 (~)

这个 Python 运算符翻转数字的所有位。如果还记得“非”运算会反转值的真实性,那么这几乎是相同的,但它侧重于二进制位。简单来说,这意味着 1 变成 0,反之亦然。

'''
Python Bitwise NOT Operator Example
'''
x = 12  # 1100 in binary
print(~x)  # Output: -13
# Note: This is a two's complement representation.
# The binary result is 11110011, which translates to -13 in integer

左移 (<<)

此 Python 运算符将数字的位向左移动指定的量,并用零填充新位。

'''
Python Left Shift Operator Example
'''
x = 5  # 0101 in binary
print(x << 1)  # Output: 10 (1010 binary, shifting bits one position to left)

右移 (>>)

此 Python 运算符将数字的位向右移动,从而删除一些最右边的位。

'''
Python Right Shift Operator Example
'''
x = 5  # 0101 in binary
print(x >> 1)  # Output: 2 (0010 binary, shifting bits one position to right)

5.赋值运算符

Python 赋值运算符是最常见的一些,它们对于在程序的整个生命周期中存储、更新和管理数据至关重要。

赋值 (=)

此 Python 赋值运算符将左侧的变量设置为右侧的值,存储和更新变量值是编程的基础。

'''
Python Assign Operator Example
'''
x = 5
print(x)  # Output: 5

添加并赋值 (+=)

此 Python 赋值运算符是一种将右操作数的值添加到左操作数,然后将结果赋给左操作数的简写方法。

'''
Python Add and Assign Operator Example
'''
x = 5
x += 3
print(x)  # Output: 8

减去并赋值 (-=)

此 Python 赋值运算符是一种从左操作数中减去右操作数的值,然后将结果赋给左操作数的简写方法。

'''
Python Subtract and Assign Operator Example
'''
x = 5
x -= 3
print(x)  # Output: 2

乘法和赋值 (*=)

此 Python 赋值运算符是将左操作数的值与右操作数相乘,然后将结果赋给左操作数的简写。

'''
Python Multiply and Assign Operator Example
'''
x = 5
x *= 3
print(x)  # Output: 15

除法和赋值 (/=)

此 Python 运算符是将左操作数的值除以右操作数,然后将结果赋给左操作数的简写。

'''
Python Divide and Assign Operator Example
'''
x = 5
x /= 2
print(x)  # Output: 2.5

取模并赋值 (%=)

此 Python 运算符是将左操作数的值除以右操作数,然后将余数结果分配给左操作数的简写。

'''
Python Modulus and Assign Operator Example
'''
x = 5
x %= 3
print(x)  # Output: 2

Floor Division 和指定 (//=)

此 Python 运算符是使用 Python // 运算符将左操作数的值除以右操作数,然后将结果赋给左操作数的简写。

'''
Python Floor Divide and Assign Operator Example
'''
x = 5
x //= 2
print(x)  # Output: 2

求幂并赋值 (=)**

此 Python 指数运算符是一种简写形式,用于将左操作数的值求右操作数的幂,然后将结果赋给左操作数。

'''
Python Exponentiate and Assign Operator Example
'''
x = 5
x **= 2
print(x)  # Output: 25

按位赋值运算符(&=、|=、^=、<<=、>>=)

这些 Python 运算符执行关联的按位运算,然后以与上面显示的其他赋值运算符相同的方式用结果更新变量。

'''
Python Bitwise Assignment Operators Example
'''
x = 5  # 0101 in binary
x &= 3  # 0011 in binary
print(x)  # Output: 1 (0001 in binary)

y = 5  # 0101 in binary
y |= 3  # 0011 in binary
print(y)  # Output: 7 (0111 in binary)

z = 5  # 0101 in binary
z ^= 3  # 0011 in binary
print(z)  # Output: 6 (0110 in binary)

a = 5  # 0101 in binary
a <<= 1
print(a)  # Output: 10 (1010 in binary)

b = 5  # 0101 in binary
b >>= 1
print(b)  # Output: 2 (0010 in binary)

6.成员运算符

Python 成员运算符可用于确定某个值是否是 Python 数据结构(如列表、元组或字符串)的成员,一般来说,这些 Python 运算符使我们可以更轻松地执行诸如在数据结构中搜索和过滤等任务。

包含(IN)

Python IN 运算符用于检查某个项目是否存在于 Python 列表等数据结构中,并返回 True 或 False。Python 成员运算符(如 IN)在与其他数据容器(如元组和字符串)交互时也很有帮助。

'''
Python "in" Membership Operator Example
'''
lst1 = [1, 2, 3, 4, 5]
print(3 in lst1)  # Output: True
print(6 in lst1)  # Output: False

不包含(not in)

此 Python 运算符用于检查容器中是否不存在某个项目(例如列表、元组或字符串),并返回 True 或 False。本质上,两个隶属度算子是互逆的。

'''
Python "not in" Membership Operator Example
'''
lst1 = [1, 2, 3, 4, 5]
print(3 not in lst1)  # Output: False
print(6 not in lst1)  # Output: True

还应该指出,在学习使用 Python 双端队列和其他更奇特的数据集合时,这两个成员运算符也很有帮助。

7.恒等运算符

Python 恒等运算符有点微妙,因为它们检查两个变量是否引用内存中完全相同的对象,而不仅仅是它们的内容是否相同。 在 Python 中使用可变数据结构时,这种区别非常重要,并且在使用恒等运算符时,必须充分了解应用程序中的数据引用和内存管理。

相等性(is)

作为两个 Python 恒等运算符之一,它用于检查两个变量是否引用内存中的同一对象以及它们的值是否相等。请记住,我们使用恒等运算符来检查对象相等性,而不仅仅是值相等性。

'''
Python "is" Identity Operator Example
'''
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z)  # Output: True ( z is same object as x)
print(x is y)  # Output: False (same content but different objects in memory)

不相等性(is not)

这个 Python 运算符用于检查两个变量是否引用内存中的不同对象。

'''
Python "is not" Identity Operator Example
'''
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is not z)  # Output: False
print(x is not y)  # Output: True

其他有用的 Python 运算符

现在已经介绍了最常见的 Python 运算符,接下来看一些展示 Python 语言的深度和多功能性的专用运算符。

其中一些对您来说可能很熟悉,而其中一些对您来说可能是新的,具体取决于您所使用的 Python 版本。

8.Walrus Operator (:=)

Walrus Operator (海象运算符)Python 3.8 中引入,正式称为赋值表达式运算符,该 Python 运算符用于将值作为表达式的一部分分配给变量。

经典用例是在列表推导式或 while 循环中,它可以为变量赋值并在一行中检查其有效性。这对于减少冗余并使代码更清晰非常有用。

'''
Python Walrus Operator Example
'''
input_text = "Hello"
if (n := len(input_text)) > 4:
   print(f"Input has {n} characters.")  # Output: Input has 5 characters.

9.Subscription ([])

Subscription(订阅 )Python 运算符主要用于访问各种数据结构(如列表、元组、字符串和字典)中的元素,将其视为订阅结构化集合中特定数据点的工具,因此得名。 无论是在开发一种算法来查找 Python 列表的长度,还是想要访问字典项,都可以使用该运算符。

'''
Python Subscription Operator Example
'''
lst2 = [1, 2, 3, 4, 5]
print(lst2[2])  # Output: 3
dict1 = {"a": 1, "b": 2}
print(dict1["a"])  # Output: 1

10.Slicing ([:])

此 Python 运算符提供了一种从列表、字符串和元组等序列中提取范围或段的机制。 Slicing(切片)很像订阅运算符,但具有更广泛的访问权限。这意味着使用切片时,可以从序列中获取一系列连续的元素,这对于数据处理来说很方便。

'''
Python Slicing Operator Example
'''
text = "Python"
print(text[1:4])  # Output: yth

Python 运算符优先级

在 Python 中,就像在数学中一样,执行操作的顺序可以极大地影响结果。这就是为什么如果想编写正确且高效的代码,则必须了解运算顺序和运算符优先级。接下来让我们看一下 Python 中操作的一般顺序,从最高优先级到最低优先级:

1.括号:首先计算括号 () 内的任何内容,这使得这是一种覆盖默认优先级的方法,或者当具有相同优先级的操作或希望某些内容具有更高优先级时更改结果。

'''
Python Operator Precedence: Parentheses
'''
result = (2 + 3) * 4  # Here, addition happens first, making result 20.

2.求幂

'''
Python Operator Precedence: Exponentiation
'''
square = 4 ** 2  # square is 16

3.一元减号:用于求反。

'''
Python Operator Precedence: Unary minus
'''
negative_value = -5

4.乘法、除法、整除法和模数:当链接在一起时,它们从左到右计算。

'''
Python Operator Precedence: Multiplication, Division, Floor Division, and Modulus
'''
result = 5 * 4 / 2  # First multiplication, then division. result is 10.0.

5.加法和减法:当它们一起出现时,从左到右计算。

'''
Python Operator Precedence: Addition and Subtraction
'''
result = 3 + 4 - 2  # First addition, then subtraction. result is 5.

6.比较运算符:可以链接多个比较,但为了清楚起见,最好使用括号。

'''
Python Operator Precedence: Comparison Operators
'''
is_true = 3 < 4 == 4  # is_true is True

7.Boolean not

'''
Python Operator Precedence: Boolean 'not'
'''
is_false = not True  # is_false is False

8.Boolean and

'''
Python Operator Precedence: Boolean 'and'
'''
result = True and False  # result is False

9.Boolean or

'''
Python Operator Precedence: Boolean 'or'
'''
result = True or False  # result is True

10.赋值和其他运算符:=、+=、-= 等赋值运算符的优先级最低。

'''
Python Operator Precedence: Assignment and other operators
'''
value = 10  # Assignment example

重要提示:虽然理解运算符优先级可以帮助您编写简洁的代码,但清晰性始终是首要任务。如果认为使用括号可能会使代码更具可读性,请继续使用它们吧!

相关推荐

关注公众号
获取免费资源

随机推荐


Copyright © Since 2014. 开源地理空间基金会中文分会 吉ICP备05002032号

Powered by TorCMS

OSGeo 中国中心 邮件列表

问题讨论 : 要订阅或者退订列表,请点击 订阅

发言 : 请写信给: osgeo-china@lists.osgeo.org