Python代码报错SyntaxError: invalid character in identifier求解决
问题解决:SyntaxError: invalid character in identifier
核心错误原因
报错行里的1e−5和1e−4使用了中文减号(−),Python仅识别英文半角减号(-),这是触发语法错误的直接原因。
完整修正后的代码
import matplotlib.pyplot as plt # 移除matplotlib与pyplot间的空格 from math import cos, pi # 补充导入pi,原代码未导入会触发NameError def f(x): """Sums Fourier series""" total = 0.0 # 避免用Python内置函数sum当变量名,防止覆盖原有功能 term = 1.0 n = 1.0 # 将中文减号替换为英文减号 while abs(term) > 1e-5 * (abs(total) + 1e-4): term = cos(n * x) / (n ** 2) # 用**2表示平方更符合Python规范 total += term # 简化累加写法 n += 2 return total n = 40 # 生成0到4π区间的采样点,计算对应f(x)值 g = [f((4 * pi * i) / n) for i in range(n)] # 绘图优化 fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) line = ax.plot(g) plt.setp(line, color='darkblue', linewidth=1.2) # 给曲线添加样式 plt.title('Fourier Series Sum (0 to 4π)') plt.xlabel('Sample Index') plt.ylabel('f(x) Value') plt.show()
额外修正说明
- 修复
matplotlib .pyplot的空格问题,避免导入失败 - 替换变量名
sum为total,规避内置函数被覆盖的风险 - 简化
sum=sum+term这类赋值语句为total += term,代码更简洁 - 给绘图添加标题、坐标轴标签和曲线样式,让可视化结果更清晰
内容的提问来源于stack exchange,提问作者David Fagbemi
相关产品推荐
相关产品推荐

