大家好我是python的新手。这是我的代码。我能够捕获Zero错误但不能捕获Name错误。我使用的是Python 3.
import re
while True:
try:
print("Lets Solve the equation (x/2)/(x-y):")
print('Please enter 0 to exit')
x= float(input('Enter the value of x:'))
y= float(input('Enter teh value of y:'))
if x==0 or y==0:
break
z = (x/2) / (x-y)
except ZeroDivisionError as e:
print('There was an error, try again ?')
print('You keyed a vlue that caused a division by 0 :')
except NameError as e:
print('There was an error, try again ?')
print('you entered a txt where a number was expected')
except Exception as e:
print('There was an error, try again ?')
print('Error mesage:',str(e))
else:
print('solving (x/2) / (x-y) for vaule of x=', \
x, 'and y:', y, 'we get the result:', z)
答案 0 :(得分:0)
对无法转换为浮点数的字符串调用float()
会导致ValueError
,而不是NameError
。
只需将第二个except
子句更改为except ValueError as e:
。