python 循环,检查输入表达式是否有误

问题遇到的现象和发生背景

python计算表达式程序,加入一个检查输入表达式是否有误的功能和循环运行功能应该怎么写
如:
input expresion:
-2*(3+5)+2^3/4=
-14
continue or not(y,n)?
y
input expression:
2 3 5+6=
Hint:the expression is wrong in format.

遇到的现象和发生背景,请写出第一个错误信息
用代码块功能插入代码,请勿粘贴截图。 不用代码块回答率下降 50%
import re
express = input("input expression:")
def caculator(eq):
    format_list = eq_format(eq)  # 把字符串变成格式化列表形式
    s_eq = simplify(format_list)  # 去括号,得到无括号的一个格式化列表
    ans = calculate(s_eq)  # 计算最终结果
    if len(ans) == 2:  # 判断最终结果为正数还是负数
        ans = -float(ans[1])
    else:
        ans = float(ans[0])
    return ans

def eq_format(eq):
    format_list = re.findall('[\d.]+|\(|\+|-|\*|/|\)', eq)
    return format_list

def simplify(format_list):
    bracket = 0  # 用于存放左括号在格式化列表中的索引
    count = 0
    for i in format_list:
        if i == '(':
            bracket = count
        elif i == ')':
            temp = format_list[bracket + 1: count]
            new_temp = calculate(temp)
            format_list = format_list[:bracket] + new_temp + format_list[count + 1:]
            format_list = change(format_list, bracket)  # 解决去括号后会出现的-- +- 问题
            return simplify(format_list)  # 递归去括号
        count = count + 1
    return format_list

def calculate(s_eq):
    if '*' or '/' in s_eq:
        s_eq = remove_multiplication_division(s_eq)
    if '+' or '-' in s_eq:
        s_eq = remove_plus_minus(s_eq)
    return s_eq

def remove_multiplication_division(eq):
    count = 0
    for i in eq:
        if i == '*':
            if eq[count + 1] != '-':
                eq[count - 1] = float(eq[count - 1]) * float(eq[count + 1])
                del (eq[count])
                del (eq[count])
            elif eq[count + 1] == '-':
                eq[count] = float(eq[count - 1]) * float(eq[count + 2])
                eq[count - 1] = '-'
                del (eq[count + 1])
                del (eq[count + 1])
            eq = change(eq, count - 1)
            return remove_multiplication_division(eq)
        elif i == '/':
            if eq[count + 1] != '-':
                eq[count - 1] = float(eq[count - 1]) / float(eq[count + 1])
                del (eq[count])
                del (eq[count])
            elif eq[count + 1] == '-':
                eq[count] = float(eq[count - 1]) / float(eq[count + 2])
                eq[count - 1] = '-'
                del (eq[count + 1])
                del (eq[count + 1])
            eq = change(eq, count - 1)
            return remove_multiplication_division(eq)
        count = count + 1
    return eq

def remove_plus_minus(eq):
    count = 0
    if eq[0] != '-':
        sum = float(eq[0])
    else:
        sum = 0.0
    for i in eq:
        if i == '-':
            sum = sum - float(eq[count + 1])
        elif i == '+':
            sum = sum + float(eq[count + 1])
        count = count + 1
    if sum >= 0:
        eq = [str(sum)]
    else:
        eq = ['-', str(-sum)]
    return eq

def change(eq, count):
    if eq[count] == '-':
        if eq[count - 1] == '-':
            eq[count - 1] = '+'
            del eq[count]
        elif eq[count - 1] == '+':
            eq[count - 1] = '-'
            del eq[count]
    return eq


result = caculator(express)
print(result)
if __name__ == '__main__':
    flag=True
    while (flag):
        judge = input("continue or not(y,n)?")
        if (judge == "n"):
            print('end')
        elif (judge == "y"):
            express = input("input expression:")

运行结果及详细报错内容
我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%
我想要达到的结果,如果你需要快速回答,请尝试 “付费悬赏”

希望最后运行界面大概如下,如果表达式格式有误会提示
input expresion:
-2*(3+5)+2^3/4=
-14
continue or not(y,n)?
y
input expression:
2 3 5+6=
Hint:the expression is wrong in format.

import re

def check_expression(expression):
  # Use a regular expression to search for the presence of a valid
  # mathematical expression in the input string. This could include
  # numbers, parentheses, and the following mathematical operators:
  # +, -, *, /, ^ (for exponentiation)
  pattern = r"^[\d.+-/*^()]+$"
  return re.search(pattern, expression) is not None

def caculator(eq):
  # Your existing caculator code goes here...

while True:
  # Get the input expression from the user
  express = input("input expression:")

  # Check if the expression is valid
  if not check_expression(express):
    # If the expression is not valid, print an error message
    print("Hint:the expression is wrong in format.")
    continue

  # If the expression is valid, evaluate it using the caculator function
  result = caculator(express)

  # Print the result of the calculation
  print(result)

  # Ask the user if they want to continue
  cont = input("continue or not(y, n)?")
  if cont.lower() != "y":
    break

你可以结合Python 的内置函数 eval() ,正则表达式和循环更高效处理这个需求。代码如下,望采纳。

import re

while True:
  # 输入表达式
  expression = input('input expression: ')

  # 使用正则表达式检查表达式的格式是否正确
  if not re.match(r'^[\d\+\-\*\/\(\)\^]+=$', expression):
    print('Hint: the expression is wrong in format.')
    continue

  # 使用 eval() 函数计算表达式的值
  try:
    result = eval(expression[:-1])
  except SyntaxError:
    print('Hint: the expression is wrong in format.')
    continue

  # 输出结果
  print(result)

  # 提示用户是否继续
  while True:
    choice = input('continue or not(y/n)? ')
    if choice == 'y':
      break
    elif choice == 'n':
      exit()
    else:
      print('Invalid choice. Please enter "y" or "n".')

img

你把没加的发出来

不知你解决了没?

如果没有,我这边可以处理。

检查代码如下:

def check(expresion):
    for v in expresion:
        if not (str(v).isdigit() or str(v) in ['+', '-', '*', '/', '^']):
            raise ValueError(f'Hint:the expression is wrong in format. {expresion}')