我在学校学习python课程我遇到了一个关于ZeroDivisionError的问题。我运行以下代码,该代码接受用户的字符串并使用正则表达式将其分解为peices。然后我计算两个分数。所有功能都有效我只有在出现零错误时才会出现问题。它终止程序,但我想在打印错误消息后使用除ZeroDivisionError子句之外的continue关键字继续循环(允许用户输入另一个等式)。
编辑:我刚刚使用IDLE运行它没有任何问题。这在PyCharm中失败了。如何修改PyCharm以捕获异常? PyCharm正在发生一些事情,而不是代码。
运行程序时出现的错误
Enter: <fraction> <operater> <fracion> >> 1/0 + 1/1
Traceback (most recent call last):
File "C:\Users\Brancucci\PycharmProjects\regex\FractionSolver.py", line
14, in <module>
X = Fraction(num, den) # create a fraction object with the lhs of the equation
File "C:\Users\Brancucci\Python\Python36-32\lib\fractions.py", line 178, in __new__
raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
ZeroDivisionError: Fraction(1, 0)
Process finished with exit code 1
这是代码
import re # used for regular expressions
from fractions import Fraction # used for fractions
# the regular expression used to extract two fractions and an operator
patt = re.compile(r'(?P<num>-?\d+)/(?P<den>-?\d+)\s*(?P<op>[+\-*/])\s*(?
P<num2>-?\d+)/(?P<den2>-?\d+)')
# loop forever until the user entered a blank string or has an error
while True:
user_string = input("Enter: <fraction> <operater> <fracion> >> ") # get
the user string
if user_string: # if the user entered something ...
data = re.findall(patt, user_string) # gives us a 5 tuple
try:
num = int(data[0][0])
den = int(data[0][1])
X = Fraction(num, den) # create a fraction object with the lhs
of the equation
num1 = int(data[0][3])
den1 = int(data[0][4])
Y = Fraction(num1, den1) # creates a fraction object with the
rhs of the equation
op = data[0][2] # extracts the operator from the user
# switch statement to apply appropriate operator to calculation
if op == '+':
R = X + Y
elif op == '-':
R = X - Y
elif op == '*':
R = X * Y
elif op == '/':
R = X / Y
else:
break
# print the results to user
print('{} = {}'.format(user_string, R))
except ZeroDivisionError:
print("Can not divide by zero")
continue
else:
break