输入无效方程时,Python计算器程序崩溃

时间:2014-02-28 06:29:05

标签: python input calculator

我遇到了关于我制作的python计算器的问题。我在python上相当新,所以请不要过于批评我。我做到了这样,当输入这样的公式时它不会崩溃:8 * d,8/0,dajf。但是,当用户输入诸如:/ 7,* e或* 6之类的内容时。它崩溃了。当输入无效的等式时,如何防止它崩溃?比方说,它只会回应“警告:无效的公式”

我目前的代码:

valid_chars = "0123456789-+/* \n";
while True:
    x = "x="
    y = input(" >> ")
     x += y
     if any(c not in valid_chars for c in y):
         print("WARNING: Invalid Equation")
         continue
     try:
         exec(x)
     except ZeroDivisionError:
         print ("WARNING: Invalid Equation")
     else:
    print(x)

提前致谢!

2 个答案:

答案 0 :(得分:2)

输入无效输入时,实际引发的异常为SyntaxError

 >> -8*
Traceback (most recent call last):
  File "Test.py", line 19, in <module>
    exec(x)
  File "<string>", line 1
    x=-8*
        ^
SyntaxError: invalid syntax

所以,您也可以简单地捕获SyntaxError,就像这样

 try:
     exec(x)
 except (ZeroDivisionError, SyntaxError):
     print ("WARNING: Invalid Equation")
 else:
     print(x)

答案 1 :(得分:0)

我最近在Python上制作了一个计算器。当我开始编写涉及分部的部分时,我简单地写道:

   if n2 == 0: //dividing by zero isn't possible
    divbyzeroerror = 1
  else:
    answer = n1 / n2
  if choice == ("a"):
answer = n1 + n2
if choice == ("s"):
answer = n1 - n2

    if(divbyzeroerror == 1): //if n2 is inputted as zero, the divbyzeroerror   variable becomes 1.  
    print("error, cannot divide by zero") //if n2 is a zero and therefore divbyzeroerror = 1, then you can get the program to print an error.
else:
print (answer)