Python写入数学等式到txt文件时出现SyntaxError语法错误求助
问题排查:写入数学等式时的SyntaxError错误
错误信息
File "
", line 1
1+1 = 2
^
SyntaxError: invalid syntax
完整代码
# function to check whether the input is operator or not def isOperator(o): if len(o) not in [1, 2]: return False return True if o in ['+', '-', '*', '/', '//', '**'] else False # function to check whether the input is number or not def isNumber(n): for i in n: if not i.isdigit(): return False return True def isFileValid(name): try: r = open(name, 'r') r.close() return True except : print('File does not exist....') return False # main function def main(): while True: print('1. Read input from User\n2. Read input from a File') choice = input('Enter choice : ') if isNumber(choice) and choice in ['1', '2']: choice = int(choice) break print('Enter valid choice') eqs = [] if choice == 1: # read input until a valid one is given while True: n1 = input('Enter number 1 : ') if isNumber(n1): break # read input until a valid one is given while True: n2 = input('Enter number 2 : ') if isNumber(n2): break # read input until a valid one is given while True: op = input('Enter operator : ') if isOperator(op): break eqs = [n1+op+n2] elif choice == 2: while True: file_name = input('Enter file name : ') if isFileValid(file_name): break r = open(file_name, 'r') if r is None: print('SS') for i in r: if '\n' in i: i = i[:-1] eqs.append(i) r.close() # create a file if it doesn't exists f = open('e.txt', 'a') for e in eqs: ans = e + '=' + str(eval(e)) # write the equation and the solution to the file f.write(ans+'\n') print(ans) # close the file f.close() if __name__ == '__main__': main()
问题原因
报错核心是eval()函数仅能执行表达式,无法处理赋值语句。当选择从文件读取输入时,如果文件内的行已包含带等号的内容(比如1+1=2),代码会直接将整行传给eval(e),而1+1=2属于赋值操作,不符合Python表达式语法,因此触发SyntaxError。
另外,当前代码的isNumber函数存在缺陷:仅允许纯数字字符串,不支持负数(如-5)和小数(如3.14),这类输入会被判定为无效。
解决方案
1. 修复文件读取的内容处理
从文件读取时,过滤掉等号及后面的内容,只保留左侧表达式:
elif choice == 2: while True: file_name = input('Enter file name : ') if isFileValid(file_name): break r = open(file_name, 'r') for i in r: i = i.strip() # 去掉首尾空白和换行符 if not i: # 跳过空行 continue # 分割等号,仅提取左侧表达式 expr = i.split('=')[0].strip() eqs.append(expr) r.close()
2. 优化isNumber函数(可选)
让函数支持负数和小数:
def isNumber(n): # 处理负数前缀 if n.startswith('-'): n = n[1:] # 限制小数点只能出现一次 if n.count('.') > 1: return False # 检查剩余字符是否为数字或小数点 for i in n: if not (i.isdigit() or i == '.'): return False return True
3. 增加错误捕获机制
在执行eval()前添加异常捕获,避免程序崩溃同时提示错误:
for e in eqs: try: result = eval(e) ans = f"{e}={result}" f.write(ans+'\n') print(ans) except SyntaxError: print(f"无效表达式:{e},跳过写入") except Exception as err: print(f"计算表达式{e}时出错:{err}")
内容的提问来源于stack exchange,提问作者Troy
相关产品推荐
相关产品推荐

