🧮 项目蓝图:从四则运算到科学计算器
今天打造了一款**"抗摔打"计算器**。项目亮点:
import math
def scientific_calc(value: float, func: str) -> float:
"""科学计算函数(支持10+种数学运算)"""
match func:
case "sqrt": return math.sqrt(value)
case "sin": return math.sin(math.radians(value)) # 角度转弧度
case "log": return math.log(value, 10)
case "fact": return math.factorial(int(value))
case _: raise ValueError(f"暂不支持{func}运算")
#.............
# 测试阶乘功能
print(scientific_calc(5, "fact")) # 输出:120
⚙️ 技术解析:math模块的正确打开方式
1. 为何要用math模块?
-
精度保障:
math.sqrt()
比**0.5
计算更稳定print(2**0.5) # 1.4142135623730951 print(math.sqrt(2)) # 1.4142135623730951 print(2**0.5 == math.sqrt(2)) # True ➡️ 看似相同... # 但当计算超大数时: big_num = 1e100 print(big_num**0.5) # 可能溢出 print(math.sqrt(big_num)) # 安全计算
2. 角度/弧度转换的奥秘
# 常见错误:直接计算90度正弦
print(math.sin(90)) # 输出0.893...(错误!)
print(math.sin(math.radians(90))) # 输出1.0(正确)
3. 阶乘的安全校验
# 错误示范
print(math.factorial(5.5)) # 报错!必须整数
# 正确做法
value = float(input("请输入阶乘数:"))
try:
print(math.factorial(int(value)))
except ValueError as e:
print(f"输入不合法:{e}")
🚨 异常处理大作战:当用户是个捣蛋鬼
场景1:输入字母假装数字
try:
num = float(input("请输入数字:"))
except ValueError:
print("亲,这里要输入数字哦~")
num = 0.0
场景2:负数开平方
def safe_sqrt(value: float):
try:
return math.sqrt(value)
except ValueError:
return complex(0, math.sqrt(abs(value))) # 返回复数
print(safe_sqrt(-9)) # 输出3j
场景3:无限递归防护
MAX_RETRY = 3 # 最大重试次数
for _ in range(MAX_RETRY):
try:
user_input = float(input("请输入:"))
break
except ValueError:
print("这是第{}次输入错误".format(_+1))
else:
print("您已输错3次,程序自闭中...")
exit()
📜 类型注解:给变量贴上智能标签
def 老式函数(a, b):
return a + b # 可能被误用
def 新时代函数(a: float, b: float) -> float:
"""明确标注参数和返回值类型"""
return a + b
# PyCharm会智能提示参数类型
# 尝试错误调用会有波浪线警告
新时代函数("你好", 123) # ❌ 类型不匹配警告
🎯 总结与知识延伸
✅ 核心收获
-
math模块的威力:
-
提供
sin/cos/log
等20+科学计算函数 -
处理特殊数值更安全(如超大数、极小数的运算)
-
-
异常处理哲学:
-
不要信任任何用户输入(包括未来的自己)
-
用
try-except
建立多道防御工事
-
-
类型注解真香定律:
-
配合PyCharm/VSCode实现智能提示
-
💡 冷知识彩蛋
-
math与cmath的区别:
import cmath print(math.sqrt(-4)) # 报错 print(cmath.sqrt(-4)) # 输出2j
-
Decimal模块的精度控制:
from decimal import Decimal print(0.1 + 0.2) # 0.30000000000000004 print(Decimal('0.1') + Decimal('0.2')) # 0.3
程序员的浪漫:当我用
math.factorial(5)
算出120时,突然明白——爱情就像阶乘函数,基础不牢(整数)就会全盘崩溃!❤️🧮
通过这次项目,我发现计算器不仅是算术工具,更是理解编程思想的绝佳载体。下次要给计算器加个彩蛋——当输入math.pi
时显示"你是我的圆周率,无限不循环~" 🥧