运算符

运算符

在Python中有各种运算符,用来处理不同数据之间的运算,主要分为以下几类:

算术运算符

运算符 名称 描述
+ 两个对象相加
- 得到负数或是一个数减去另一个数
* 两个数相乘或返回一个被重复若干次的字符串
/ x除以y
% 取模(取余),模运算 返回除法的余数
** 幂(指数) 返回x的y次幂
// 取整除 返回商的整数部分(向下取整)
Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1
>>> b = 2
>>> a + 1
2
>>> a - b
-1
>>> a * b
2
>>> a / b
0.5
>>> a % b
1
>>> a // b
0
>>> a ** b
1
>>> b ** 2
4
>>>

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

返回的是布尔值

运算符 描述
== 等于:比较对象是否相等
!= 不等于:比较两个对象是否不相等
> 大于:返回x是否大于y
< 小于:返回x是否小于y
">=" 大于等于:返回x是否大于等于y
"<=" 小于等于:返回x是否小于等于y
Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 5
>>> b = 2
>>> a == b
False
>>> a != b
True
>>> a > b
True
>>> a < b
False
>>> a >= b
True
>>> a <= b
False
>>>

赋值运算符

简单基础的赋值运算符:=

扩展赋值运算符:例如:+= (a+=b)等效于(a = a + b) 以此类推

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 4
>>> b = 3
>>> a += b
>>> a
7
>>>

逻辑运算符

运算符 逻辑表达式 描述
and x and y x和y都为True则为True,否则为False
or x or y x和y其中一个为True就为True,都为False则为False
not not x 取反
Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1
>>> b = 0
>>> a and b
0
>>> a or b
1
>>> not a
False
>>> not b
True
>>>

成员运算符

运算符 描述
in 如果在指定的序列中找到值返回True,否则返回False
not in 如果在指定的序列中没有找到返回True,否则返回False
Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> l = ['linux','python','java']
>>> if 'python' in l:
...     print("111111")
...
111111
>>> 'linux' in l
True
>>> 'git' in l
False
>>> 'git' not in l
True
>>>

身份运算符

运算符 描述
is is是判断两个标识符是不是引用自一个对象,返回布尔值
is not 与上面相反
Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'Hello'
>>> a is 'Hello'
<stdin>:1: SyntaxWarning: "is" with 'str' literal. Did you mean "=="?
True
>>> a is not 'Hello'
<stdin>:1: SyntaxWarning: "is not" with 'str' literal. Did you mean "!="?
False
>>> a is not 'xxxx'
<stdin>:1: SyntaxWarning: "is not" with 'str' literal. Did you mean "!="?
True
>>>

运算符优先级

这里不赘述,与我们学习的数学一致,可以用括号括起来提升优先级,先乘除后加减等。

posted on 2025-06-15 20:56  burgess0x  阅读(17)  评论(0)    收藏  举报