所以我需要制作一个计算器,将字符串转换为浮点数然后计算。 问题是我需要在以下情况下发出错误消息:
这是代码看起来没有错误消息的方式
# Interface
print ("Equation Calculator")
print (" ")
print ("My Equation Calculator is able to")
print (" Add: +")
print (" Subtract: -")
print (" Multiply: *")
print (" Divide: /")
print (" ")
print ("The equation you enter must follow this syntax:")
print (" <openrand><speace><operator><space><operand>.")
print ("An <operand> is any float number.")
print ("An <operator> is any is any of the operators mentioned above.")
print ("A <space> is an empty space.")
# Enter the equation
equation = input ("Enter your equation: ")
# Split the equation into Operand 1,2 and Operator
operand1,operator,operand2 = equation.split(" ")
# Show the user the equation
print ("Here is the equation you have entered: " + equation)
# Addition, Converting strings (operand 1 and 2) into float
if (operator == "+"):
answer = float(operand1) + float(operand2)
# Subtraction, Converting strings (operand 1 and 2) into float
if (operator == "-"):
answer = float(operand1) - float(operand2)
# Multiplication, Converting strings (operand 1 and 2) into float
if (operator == "*"):
answer = float(operand1) * float(operand2)
# DIvision, Converting strings (operand 1 and 2) into float
if (operator == "/"):
answer = float(operand1) / float(operand2)
# Display the answer
print ("The answer is: ",answer )
因此,对于第7和第8个错误,我做了这个
# Error for not having a space
if (equation.find(" ") == False):
print ("Error #1: Please check if there is a space in between the two operands and the operator.")
# Error for dividing by 0
if (operand2 == "0"):
print ("Error #7: You cannot divide by 0.")
但是python只是绕过了这个并且仍然崩溃了。 上面的代码有什么问题? 我怎样才能使代码在上述8种情况下打印错误信息? 另外我不能使用内置函数eval()或exec(),break或continue或pass或sys.exit()。 我对编程很新。 请帮忙,谢谢。
答案 0 :(得分:1)
如果您对传入数据有一些设置要求,通常最好先检查数据是否符合此要求。 所以我会测试给定的字符串是否符合您的要求: 可以使用正则表达式测试一般结构:
我假设只使用整数,如果不是,你需要用浮动点匹配替换\ ds,这应该是可谷歌的。
\d+ [+\/\-*] \d+
这个正则表达式匹配任何数字,后跟一个空格,后跟一个运算符+ / * - 和一个数字。
请注意,这不会导致非常一般的错误消息 - 例如“您的输入看起来不像所需的输入”,因此您可能更好地分别测试这些部分,以提供更好的用户体验。
答案 1 :(得分:0)
使用这样的结构:
if bad_condition:
print "error"
else:
# do whatever
答案 2 :(得分:0)
你可以试试这个:
try:
assert condition, "Error Message"
except AssertionError, e:
raise Exception(e.args)
例如:
# Error for not having a space
try:
assert (equation.find(" ")), "Error #1: Please check if there is a space in between the two operands and the operator."
except AssertionError, e:
raise Exception(e.args)