​AI数学启蒙:100天Python实践计划(小学水平起步)​【第2天:加减法】

Python3 加减法运算详解

Python3 中的加减法是最基础的数学运算,但掌握其各种用法和技巧对于编程非常重要。以下是关于 Python3 加减法运算的全面详解。

1. 基本加减法运算

整数加减法

a = 10
b = 3

# 加法
sum_result = a + b  # 13

# 减法
diff_result = a - b  # 7

浮点数加减法

x = 5.5
y = 2.2

# 加法
float_sum = x + y  # 7.7

# 减法
float_diff = x - y  # 3.3

2. 加减法运算符重载

Python 允许自定义类的加减法运算:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)
    
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(2, 3)
v2 = Vector(1, 1)

print(v1 + v2)  # Vector(3, 4)
print(v1 - v2)  # Vector(1, 2)

3. 复数加减法

Python 内置支持复数运算:

# 复数定义
c1 = 3 + 4j
c2 = 1 - 2j

# 加法
c_add = c1 + c2  # (4+2j)

# 减法
c_sub = c1 - c2  # (2+6j)

print(c_add, c_sub)

4. 链式加减法

Python 支持链式运算:

a = 10
result = a + 5 - 3 + 2  # 相当于 ((10 + 5) - 3) + 2
print(result)  # 14

5. 加减法与赋值结合

a = 10

# 加法赋值
a += 5  # 相当于 a = a + 5
print(a)  # 15

# 减法赋值
a -= 3  # 相当于 a = a - 3
print(a)  # 12

6. 加减法与字符串连接

+ 运算符也可用于字符串连接:

str1 = "Hello"
str2 = "World"

# 字符串连接
combined = str1 + " " + str2  # "Hello World"

# 注意:字符串不支持减法
# str3 = str1 - "llo"  # 这会引发 TypeError

7. 加减法与列表/元组连接

+ 可用于合并序列:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

# 列表合并
merged_list = list1 + list2  # [1, 2, 3, 4, 5, 6]

# 元组合并
tuple1 = (1, 2)
tuple2 = (3, 4)
merged_tuple = tuple1 + tuple2  # (1, 2, 3, 4)

# 注意:列表和元组不支持减法

8. 加减法与集合运算

虽然 + 不适用于集合,但集合有专门的并集和差集运算:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# 并集(类似加法)
union = set1 | set2  # {1, 2, 3, 4, 5}

# 差集(类似减法)
difference = set1 - set2  # {1, 2}

9. 加减法与位运算

Python 的位运算符 &|^~ 可以看作是二进制位的加减法:

a = 5  # 二进制 0101
b = 3  # 二进制 0011

# 按位与(类似最小值)
bit_and = a & b  # 1 (0001)

# 按位或(类似最大值)
bit_or = a | b   # 7 (0111)

# 按位异或
bit_xor = a ^ b  # 6 (0110)

# 按位取反
bit_not = ~a     # -6 (补码表示)

10. 加减法与浮点数精度问题

浮点数运算可能存在精度问题:

a = 0.1
b = 0.2

# 看似简单的加法
result = a + b  # 0.30000000000000004

# 解决方案:使用decimal模块
from decimal import Decimal

a_dec = Decimal('0.1')
b_dec = Decimal('0.2')
precise_result = a_dec + b_dec  # 0.3

11. 加减法与数学函数

结合 math 模块进行更复杂的运算:

import math

a = 10
b = 3

# 加法后取整
result = math.floor(a + b / 2)  # 11

# 减法后取绝对值
diff = math.fabs(a - b * 4)  # 2.0

12. 加减法与条件表达式

a = 10
b = 20

# 使用三元运算符
max_value = a if a > b else a + b - a  # 等同于 max(a, b)

# 或者更简单的写法
max_value = max(a, b)

13. 加减法与列表推导式

numbers = [1, 2, 3, 4, 5]

# 列表元素加1
plus_one = [x + 1 for x in numbers]  # [2, 3, 4, 5, 6]

# 列表元素减1
minus_one = [x - 1 for x in numbers]  # [0, 1, 2, 3, 4]

14. 加减法与生成器表达式

# 生成1到10的数字加5的生成器
gen = (x + 5 for x in range(1, 11))

# 使用生成器
for num in gen:
    print(num, end=' ')  # 输出6 7 8 9 10 11 12 13 14 15

15. 加减法与numpy数组运算

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# 数组加法
arr_sum = arr1 + arr2  # array([5, 7, 9])

# 数组减法
arr_diff = arr2 - arr1  # array([3, 3, 3])

# 广播机制
arr_sum_broadcast = arr1 + 5  # array([6, 7, 8])

16. 加减法与pandas数据运算

import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})

# 列加法
df['C'] = df['A'] + df['B']  # 新增列C,值为A+B

# 行加法
df['D'] = df.sum(axis=1)  # 新增列D,值为每行总和

# 减法
df['E'] = df['B'] - df['A']  # 新增列E,值为B-A

17. 加减法与时间计算

from datetime import datetime, timedelta

# 创建时间点
start_time = datetime(2023, 1, 1)
end_time = datetime(2023, 1, 10)

# 时间差(减法)
delta = end_time - start_time  # 9天
print(delta.days)  # 9

# 时间加法
new_time = start_time + timedelta(days=5)  # 2023-01-06

18. 加减法与自定义精度计算

from decimal import Decimal, getcontext

# 设置精度
getcontext().prec = 6

a = Decimal('0.1')
b = Decimal('0.2')

result = a + b  # 0.3 (精确表示)

19. 加减法与金融计算

# 计算股票价格变化
initial_price = 100.0
final_price = 105.5

# 百分比变化
change_percent = ((final_price - initial_price) / initial_price) * 100  # 5.5%

# 金额变化
amount_change = final_price - initial_price  # 5.5

20. 加减法与错误处理

def safe_add(a, b):
    try:
        return a + b
    except TypeError:
        return "无法相加的类型"

print(safe_add(1, 2))      # 3
print(safe_add("1", 2))    # 无法相加的类型
print(safe_add([1], [2]))  # [1, 2] (列表可以相加)

总结

Python 中的加减法运算虽然基础,但通过与其他特性的结合可以产生强大的功能。掌握这些进阶用法可以帮助你编写更高效、更灵活的代码。在实际应用中,根据具体场景选择合适的加减法实现方式非常重要。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韩公子的Linux大集市

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值