所以我使用 python 2.7.8 制作了一个计算器,一切正常,除非有一件事。我想收到错误消息“错误:最小输入:数字操作员号码!”例如,当我尝试计算“2 +”时。但我无法让它工作。如果有人能指出我犯了什么错误,那就太好了。 这是无法正常工作的地方:
except len(self.input) < 3:
print "ERROR: Minimum Input: Number Operator Number!"
这里是整个代码:
import sys
class Calculator(object):
def __init__(self, input):
self.input = input
def divide(self, number1, number2):
return number1 / number2
def add(self, number1, number2):
return number1 + number2
def sub(self, number1, number2):
return number1 - number2
def mult(self, number1, number2):
return number1 * number2
def modulo(self, number1, number2):
return number1 % number2
def exponentiate(self, number1, number2):
return number1 ** number2
def print_error(self, error):
print error
sys.exit(-1)
def print_result(self, result):
print result
sys.exit(0)
def process_input(self):
try:
result = float(self.input[1])
current_operator = ""
for element in self.input[2:]:
if element in ["/", "+", "-", "*", "%", "**"]:
current_operator = element
else:
number2 = float(element)
if current_operator == "/":
result = self.divide(result, number2)
elif current_operator == "+":
result = self.add(result, number2)
elif current_operator == "-":
result = self.sub(result, number2)
elif current_operator == "*":
result = self.mult(result, number2)
elif current_operator == "%":
result = self.modulo(result, number2)
elif current_operator == "**":
result = self.exponentiate(result, number2)
else:
self.print_error(error)
self.print_result(result)
except ZeroDivisionError:
print "ERROR: Caught division by zero!"
except ValueError:
print "ERROR: Input number could not be parsed!"
except OverflowError:
print "ERROR: Result too large! Overflow encountered."
except len(self.input) < 3:
print "ERROR: Minimum Input: Number Operator Number!"
calc = Calculator(sys.argv)
calc.process_input()
感谢您的回答!
如您所见,代码将无法运行。相反,您需要将此部分更改为
if
语句或手动 raise
异常:
try:
# ...code...
except len(self.input) < 3:
print "ERROR: Minimum Input: Number Operator Number!"
if len(self.input) < 3:
print "ERROR: Minimum Input: Number Operator Number!"
else:
# ...code...
try:
if len(self.input) < 3:
raise RuntimeError("Not enough arguments.")
# ...code...
except RuntimeError:
print "ERROR: Minimum Input: Number Operator Number!"
我用
RuntimeError
作为例子,你可能想用更合适的代替。
try:
assert len(self.input) >= 3
# ...Your code...
except AssertionError:
print "ERROR: Minimum Input: Number Operator Number!"
问题是“except”后面必须跟一个异常,而“len(self.input) >= 3”也不例外! (AssertionError 是个例外)
user_info = input("Enter the following info- Name Age Favorite Sport: ") user_info_split = user_info.split() 打印“你好,” + user_info_split[0] + “!” + “我也喜欢” + user_info_split[2] + “!”