Python中异常处理的问题
我的代码在传播异常时遇到以下问题: 代码应该做什么:Python中异常处理的问题,python,exception-handling,Python,Exception Handling,我的代码在传播异常时遇到以下问题: 代码应该做什么: class Calculator(): def power(self,n,p): self.n=n self.p=p try: raise NameError("n and p should be non-negative") except NameError: a=pow(n,p) return
class Calculator():
def power(self,n,p):
self.n=n
self.p=p
try:
raise NameError("n and p should be non-negative")
except NameError:
a=pow(n,p)
return a
myCalculator=Calculator()
T=int(raw_input())
for i in range(T):
n,p = map(int, raw_input().split())
try:
ans=myCalculator.power(n,p)
print ans
except Exception,e:
print e
243
16
1.0
-1
它需要输入要运行的大量组合或测试用例
它取n=number,其幂=p。(即2^3=8
)
如果p和n为正,它需要打印2^3=8
并返回它-这是有效的
如果n或p为负数,则需要打印“n和p应为非负数”-这不起作用
我的代码:
class Calculator():
def power(self,n,p):
self.n=n
self.p=p
try:
raise NameError("n and p should be non-negative")
except NameError:
a=pow(n,p)
return a
myCalculator=Calculator()
T=int(raw_input())
for i in range(T):
n,p = map(int, raw_input().split())
try:
ans=myCalculator.power(n,p)
print ans
except Exception,e:
print e
243
16
1.0
-1
给定的输入
4
3 5
2 4
-1 -2
-1 3
收到的输出:
class Calculator():
def power(self,n,p):
self.n=n
self.p=p
try:
raise NameError("n and p should be non-negative")
except NameError:
a=pow(n,p)
return a
myCalculator=Calculator()
T=int(raw_input())
for i in range(T):
n,p = map(int, raw_input().split())
try:
ans=myCalculator.power(n,p)
print ans
except Exception,e:
print e
243
16
1.0
-1
但是,对于第3个和第4个测试用例,我应该收到“n和p应该是非负的”,因为最后2个测试用例(测试用例编号3和4)的值都设置为负
出什么问题了?您实际上没有检查这些值。你想要那样的东西吗
class Calculator():
def power(self,n,p):
self.n=n
self.p=p
if n<0 or p<0:
raise NameError("n and p should be non-negative")
a=pow(n,p)
return a
class计算器():
def电源(自身、n、p):
self.n=n
self.p=p
如果您没有实际测试值是否为正值..我之前也尝试过另一种方法,但也不起作用,请原谅,因为我是一个新的bee:class Calculator():def power(self,n,p):self.n=n self.p=p try:如果n>0和p>0:a=pow(n,p)返回a,但值错误除外,e:print“n和p应该是非负的”:我会尝试您的代码并让您知道是的,您绝对正确,我发现了我的错误并找出了我做错的地方。谢谢你