Python 基础详解:运算符(Operators)—— 程序的“计算引擎”

一、什么是运算符?

在 Python 编程中,运算符(Operators) 是用于对变量和值执行特定操作的符号。它们是构建程序逻辑的核心工具,就像数学中的加减乘除一样。

例如:

a = 10 + 5  # + 是加法运算符

二、Python 运算符分类概览

类别

运算符

说明

算术运算符

+, -, *, /, //,%, **

数值计算

比较运算符

==, !=, >, <, >=, <=

比较大小,返回布尔值

赋值运算符

=,+=,-=,*=,/=, //=, %=, **=

给变量赋值

逻辑运算符

and, or, not

逻辑判断

成员运算符

in, not in

判断元素是否在序列中

身份运算符

is, is not

判断两个变量是否指向同一对象

位运算符

&, `

, ^, ~, <<, >>`

💡 本文将重点讲解前六类最常用运算符。


三、算术运算符(Arithmetic Operators)

用于执行基本的数学运算。

运算符

名称

示例

结果

+

加法

10 + 3

13

-

减法

10 - 3

7

*

乘法

10 * 3

30

/

除法

10 / 3

3.333...

//

整除(地板除)

10 // 3

3

%

取余(模运算)

10 % 3

1

**

幂运算

10 ** 3

1000

详细说明:

1. /// 的区别
print(10 / 3)   # 3.3333333333333335 (浮点数)
print(10 // 3)  # 3 (整数)
print(10.0 // 3) # 3.0 (结果为 float,但值是整数部分)

// 总是向下取整(向负无穷方向)。

2. % 取余运算
print(10 % 3)   # 1
print(-10 % 3)  # 2 (结果为正数,遵循数学定义)
3. ** 幂运算
print(2 ** 3)   # 8
print(4 ** 0.5) # 2.0 (平方根)

四、比较运算符(Comparison Operators)

用于比较两个值,返回布尔值TrueFalse)。

运算符

名称

示例

结果

==

等于

10 == 3

False

!=

不等于

10 != 3

True

>

大于

10 > 3

True

<

小于

10 < 3

False

>=

大于等于

10 >= 3

True

<=

小于等于

10 <= 3

False

使用示例:

age = 25
price = 19.99
name = "Alice"

print(age == 25)        # True
print(price != 20.00)   # True
print(age > 18)         # True
print(name == "alice")  # False (区分大小写)

⚠️ 注意:== 是比较,= 是赋值!


五、赋值运算符(Assignment Operators)

用于给变量赋值。

运算符

示例

等价于

=

x = 5

x = 5

+=

x += 3

x = x + 3

-=

x -= 3

x = x - 3

*=

x *= 3

x = x * 3

/=

x /= 3

x = x / 3

//=

x //= 3

x = x // 3

%=

x %= 3

x = x % 3

**=

x **= 3

x = x ** 3

使用示例:

x = 10
print(x)  # 10

x += 5    # 相当于 x = x + 5
print(x)  # 15

x *= 2    # 相当于 x = x * 2
print(x)  # 30

x **= 2   # 相当于 x = x ** 2
print(x)  # 900

优势:代码更简洁,是 Python 编程中的常见写法。


六、逻辑运算符(Logical Operators)

用于组合多个条件,返回布尔值

运算符

含义

真值表

示例

and

与(都为真才真)

True and True → True

True and False → False

False and False → False

(age > 18) and (has_license == True)

or

或(有一个真就真)

True or True → True

True or False → True

False or False → False

(is_student == True) or (age < 12)

not

非(取反)

not True → False

not False → True

not (age < 18)

使用示例:

age = 25
is_student = True
has_job = False

# and: 年龄大于18 且 是学生
print(age > 18 and is_student)  # True

# or: 是学生 或 有工作
print(is_student or has_job)    # True

# not: 不是学生
print(not is_student)           # False

# 复杂条件
can_vote = age >= 18 and not has_job
print(can_vote)  # True(假设 25 岁且无工作)

💡 短路求值and 遇到 False 立即返回 Falseor 遇到 True 立即返回 True,后面的表达式不再计算。


七、成员运算符(Membership Operators)

用于检查一个值是否在序列(如字符串、列表、元组、字典的键)中。

运算符

含义

示例

结果

in

在...中

"a" in "abc"

True

not in

不在...中

"d" not in "abc"

True

使用示例:

fruits = ["苹果", "香蕉", "橙子"]
name = "Alice"
student = {"name": "Bob", "age": 20}

print("苹果" in fruits)        # True
print("葡萄" not in fruits)    # True

print("A" in name)             # True
print("z" in name)             # False

# 字典中检查的是**键**(key)
print("name" in student)       # True
print("Bob" in student)        # False ("Bob" 是值,不是键)
print("Bob" in student.values()) # True (检查值)

应用场景:验证用户输入、检查列表中是否存在某元素。


八、身份运算符(Identity Operators)

用于判断两个变量是否指向同一个对象(内存地址相同)。

运算符

含义

示例

is

是同一个对象

a is b

is not

不是同一个对象

a is not b

== 的区别:

  • == 比较的是是否相等
  • is 比较的是身份(内存地址)是否相同
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)    # True (值相等)
print(a is b)    # False (不同的列表对象)
print(a is c)    # True (c 是 a 的引用,指向同一对象)

# 特殊情况:小整数和短字符串的缓存
x = 100
y = 100
print(x is y)    # True (Python 缓存了小整数)

x = 1000
y = 1000
print(x is y)    # 可能为 False (大整数不缓存,取决于实现)
print(x == y)    # True

⚠️ 建议:通常使用 == 比较值,is 仅用于与 None 比较:

if user is None:
    print("用户未登录")

九、运算符优先级(Operator Precedence)

当表达式中包含多个运算符时,Python 会按照优先级顺序执行。

优先级从高到低(部分):

优先级

运算符

说明

1

**

幂运算

2

+x, -x, ~x

正负号、按位取反

3

*, /, //, %

乘、除、整除、取余

4

+, -

加、减

5

<, <=, >, >=, ==, !=

比较

6

not

逻辑非

7

and

逻辑与

8

or

逻辑或

9

=

赋值

使用括号 () 控制优先级

result = 10 + 5 * 2     # 先乘后加 → 20
result = (10 + 5) * 2   # 先加后乘 → 30

complex_cond = (age > 18 and is_student) or (has_license and not has_debt)

最佳实践:使用括号明确表达意图,提高代码可读性。


十、综合示例:学生成绩判断系统

# 学生信息
name = "张三"
score = 85
is_attendance_good = True
has_submitted_project = True

# 判断是否优秀
is_excellent = (score >= 90) and is_attendance_good
print(f"{name} 是否优秀?{is_excellent}")  # False

# 判断是否有资格参加竞赛
can_compete = (score >= 80) and has_submitted_project
print(f"{name} 能参加竞赛吗?{can_compete}")  # True

# 判断是否需要补考
needs_retake = score < 60
print(f"{name} 需要补考吗?{needs_retake}")  # False

# 使用成员运算符检查科目
subjects = ["数学", "语文", "英语"]
print("数学" in subjects)  # True
print("物理" not in subjects)  # True

十一、总结:运算符核心要点

类别

关键点

使用场景

算术

/返回 float,//是整除,

% 取余

数值计算

比较

返回 True/False== 比较值

条件判断

赋值

+=, *=等复合赋值更简洁

变量更新

逻辑

and(都真才真),

or(一真即真),

not(取反)

组合条件

成员

in检查元素是否存在

验证、搜索

身份

is比较对象身份,常用于 is None

判断是否为同一对象

学习建议:

  1. 熟练掌握算术、比较、赋值运算符—— 这是最基础的。
  2. 理解 and/or/not 的逻辑,它们是构建复杂条件的关键。
  3. 善用 in 检查列表、字符串中的元素
  4. 记住 == is 的区别,避免常见陷阱。
  5. 使用括号 () 明确优先级,让代码更清晰。

📌 动手练习

  1. 写一个程序,判断一个年份是否为闰年。
  2. 检查一个字符串是否包含特定关键词。
  3. 判断用户是否有权限访问某个功能(需满足多个条件)。
# 闰年判断(能被4整除但不能被100整除,或者能被400整除)
year = 2024
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(f"{year} 是闰年吗?{is_leap}")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值