Skip to content

运算符

掌握 Python 的计算语言 —— 从算术到逻辑


运算符概览

运算符是执行特定操作的符号。Python 有以下几类运算符:

类别示例用途
算术运算符+, -, *, /数学计算
比较运算符==, !=, >, <比较大小
逻辑运算符and, or, not逻辑判断
赋值运算符=, +=, -=变量赋值
成员运算符in, not in检查成员关系

算术运算符

基本运算

python
a = 10
b = 3

print(a + b)   # 13  加法
print(a - b)   # 7   减法
print(a * b)   # 30  乘法
print(a / b)   # 3.333... 除法(结果为浮点数)
print(a // b)  # 3   整除(向下取整)
print(a % b)   # 1   取模(余数)
print(a ** b)  # 1000 幂运算(10的3次方)

对比 Stata/R

操作PythonStataR
加法a + ba + ba + b
减法a - ba - ba - b
乘法a * ba * ba * b
除法a / ba / ba / b
整除a // bfloor(a/b)a %/% b
取模a % bmod(a, b)a %% b
幂运算a ** ba^ba^ba**b

实战示例:收入税计算

python
# 年收入
annual_income = 85000

# 累进税率
if annual_income <= 50000:
    tax = annual_income * 0.10
elif annual_income <= 100000:
    tax = 50000 * 0.10 + (annual_income - 50000) * 0.20
else:
    tax = 50000 * 0.10 + 50000 * 0.20 + (annual_income - 100000) * 0.30

tax_rate_effective = (tax / annual_income) * 100
net_income = annual_income - tax

print(f"年收入: ${annual_income:,}")
print(f"应缴税: ${tax:,.2f}")
print(f"实际税率: {tax_rate_effective:.2f}%")
print(f"税后收入: ${net_income:,.2f}")

输出

年收入: $85,000
应缴税: $12,000.00
实际税率: 14.12%
税后收入: $73,000.00

️ 比较运算符

比较运算符返回布尔值(TrueFalse)。

python
x = 10
y = 20

print(x == y)  # False  等于
print(x != y)  # True   不等于
print(x > y)   # False  大于
print(x < y)   # True   小于
print(x >= y)  # False  大于等于
print(x <= y)  # True   小于等于

️ 注意:= vs ==

python
# = 是赋值
age = 25

# == 是比较
is_adult = (age == 18)  # False

实战示例:筛选受访者

python
# 受访者数据
age = 35
income = 75000
education_years = 16

# 筛选条件:25-45岁、收入5-10万、至少本科
is_target_group = (
    (age >= 25 and age <= 45) and
    (income >= 50000 and income <= 100000) and
    (education_years >= 16)
)

print(f"是否为目标人群: {is_target_group}")  # True

逻辑运算符

逻辑运算符用于组合多个条件。

1. and(与)- 所有条件都为真

python
age = 30
has_job = True

is_eligible = (age >= 18) and has_job
print(is_eligible)  # True(两个条件都满足)

# 任何一个为 False,结果就是 False
is_eligible = (age >= 50) and has_job
print(is_eligible)  # False

真值表

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

2. or(或)- 任一条件为真

python
has_bachelors = True
has_masters = False

has_degree = has_bachelors or has_masters
print(has_degree)  # True(至少一个为真)

# 两个都为 False,结果才是 False
has_degree = (has_bachelors == False) or (has_masters == False)
print(has_degree)  # True

真值表

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

3. not(非)- 取反

python
is_student = False
is_employed = not is_student
print(is_employed)  # True

# 双重否定
is_student = True
is_not_student = not is_student  # False
is_student_again = not is_not_student  # True

组合使用

python
# 复杂条件:筛选失业的年轻人或高收入者
age = 25
is_employed = False
income = 120000

is_target = (age < 30 and not is_employed) or (income > 100000)
print(is_target)  # True

对比 Stata/R

操作PythonStataR
and&&&&
or``
not!!

Stata 示例

stata
* Stata
gen is_eligible = (age >= 18 & age <= 65) & (income > 0)

R 示例

r
# R
is_eligible <- (age >= 18 & age <= 65) & (income > 0)

Python 示例

python
# Python
is_eligible = (age >= 18 and age <= 65) and (income > 0)

赋值运算符

基本赋值

python
x = 10  # 基本赋值

复合赋值运算符

python
x = 10

x += 5   # 等价于 x = x + 5   → 15
x -= 3   # 等价于 x = x - 3   → 12
x *= 2   # 等价于 x = x * 2   → 24
x /= 4   # 等价于 x = x / 4   → 6.0
x //= 2  # 等价于 x = x // 2  → 3.0
x %= 2   # 等价于 x = x % 2   → 1.0
x **= 3  # 等价于 x = x ** 3  → 1.0

print(x)  # 1.0

实战示例:累计计算

python
# 计算总分
total_score = 0

# 逐项加分
total_score += 85  # 数学成绩
total_score += 92  # 英语成绩
total_score += 78  # 物理成绩

print(f"总分: {total_score}")  # 总分: 255

# 计算平均分
total_score /= 3
print(f"平均分: {total_score:.2f}")  # 平均分: 85.00

成员运算符

innot in

python
# 检查元素是否在序列中
majors = ['Economics', 'Sociology', 'Political Science']

print('Economics' in majors)  # True
print('Physics' in majors)    # False
print('Physics' not in majors)  # True

# 检查子字符串
email = "alice@university.edu"
print('@' in email)  # True
print('university' in email)  # True

实战示例:专业分类

python
# 社科专业列表
social_science_majors = [
    'Economics', 'Sociology', 'Political Science',
    'Psychology', 'Anthropology'
]

# 检查学生专业
student_major = 'Economics'

if student_major in social_science_majors:
    print(f"{student_major} 属于社会科学")
else:
    print(f"{student_major} 不属于社会科学")

# 输出: Economics 属于社会科学

运算符优先级

从高到低:

  1. () 括号
  2. ** 幂运算
  3. *, /, //, % 乘除运算
  4. +, - 加减运算
  5. ==, !=, >, <, >=, <= 比较运算
  6. not 逻辑非
  7. and 逻辑与
  8. or 逻辑或

示例

python
# 复杂表达式
result = 2 + 3 * 4 ** 2 > 50 and not False
# 计算顺序:
# 1. 4 ** 2 = 16
# 2. 3 * 16 = 48
# 3. 2 + 48 = 50
# 4. 50 > 50 = False
# 5. not False = True
# 6. False and True = False
print(result)  # False

# 使用括号明确顺序
result = ((2 + 3) * 4) ** 2 > 50 and (not False)
# 1. 2 + 3 = 5
# 2. 5 * 4 = 20
# 3. 20 ** 2 = 400
# 4. 400 > 50 = True
# 5. not False = True
# 6. True and True = True
print(result)  # True

建议:复杂表达式用括号明确优先级!


实战案例:数据质量检查

python
# 受访者数据
respondent_id = 1001
age = 35
gender = "Male"
income = 75000
education_years = 16
marital_status = "Married"

# === 数据质量检查 ===

# 1. 年龄合理性(18-100岁)
is_age_valid = 18 <= age <= 100

# 2. 性别合理性
valid_genders = ["Male", "Female", "Other"]
is_gender_valid = gender in valid_genders

# 3. 收入合理性(非负且不过高)
is_income_valid = 0 <= income <= 10000000

# 4. 教育年限合理性(0-30年)
is_education_valid = 0 <= education_years <= 30

# 5. 婚姻状况合理性
valid_marital = ["Single", "Married", "Divorced", "Widowed"]
is_marital_valid = marital_status in valid_marital

# === 总体判断 ===
is_data_valid = (
    is_age_valid and
    is_gender_valid and
    is_income_valid and
    is_education_valid and
    is_marital_valid
)

# === 输出报告 ===
print(f"受访者 {respondent_id} 数据质量检查:")
print(f"  年龄: {'' if is_age_valid else ''}")
print(f"  性别: {'' if is_gender_valid else ''}")
print(f"  收入: {'' if is_income_valid else ''}")
print(f"  教育: {'' if is_education_valid else ''}")
print(f"  婚姻: {'' if is_marital_valid else ''}")
print(f"  总体: {' 通过' if is_data_valid else ' 未通过'}")

常见错误

错误 1:混淆 ===

python
age = 25      #  赋值
if age = 25:  #  SyntaxError
if age == 25: #  比较

错误 2:链式比较理解错误

python
# Python 支持链式比较(很方便!)
age = 30
result = 18 <= age <= 65  #  True(相当于 age >= 18 and age <= 65)

# 不要这样写(虽然语法正确但逻辑错误)
result = age >= 18 and <= 65  #  SyntaxError

错误 3:逻辑运算符拼写错误

python
result = True && False  #  SyntaxError(这是 JavaScript 语法)
result = True and False #  Python 用 and

练习题

练习 1:BMI 计算与分类

python
# 给定数据
height_cm = 175
weight_kg = 70

# 任务:
# 1. 计算 BMI (weight / (height_m ** 2))
# 2. 判断分类:
#    - BMI < 18.5: 偏瘦
#    - 18.5 <= BMI < 25: 正常
#    - 25 <= BMI < 30: 超重
#    - BMI >= 30: 肥胖

练习 2:复杂筛选条件

python
# 给定数据
age = 28
income = 65000
education = "Bachelor's"
has_job = True
city = "Beijing"

# 任务:筛选符合以下条件的人
# 1. 年龄在 25-35 岁之间
# 2. 收入在 5-10 万之间
# 3. 至少本科学历 或 有工作
# 4. 居住在一线城市(Beijing, Shanghai, Guangzhou, Shenzhen)

练习 3:数据验证

python
# 给定问卷数据
q1_age = 25
q2_income = -5000  # 可能有错误
q3_satisfaction = 7  # 满意度(1-5)
q4_email = "alice.example.com"  # 缺少 @

# 任务:检查每个问题的数据是否合理
# 1. 年龄: 18-100
# 2. 收入: >= 0
# 3. 满意度: 1-5
# 4. 邮箱: 包含 @

下一步

在下一节中,我们将学习 条件语句(if-else),利用今天学的运算符进行决策。

继续前进!

基于 MIT 许可证发布。内容版权归作者所有。