gpt4 book ai didi

Python Koan 131 引发异常

转载 作者:行者123 更新时间:2023-11-28 21:28:41 25 4
gpt4 key购买 nike

这几天通过做Python Koans来学习Python,遇到了Python中引发异常的问题。具体来说,在看完公案之后,我什至对 try... except... 感到困惑。我知道鲁迪·科恩 (Rudy Koan) 也有类似的问题 Ruby Koan 151 raising exceptions 。但我是一个Python新手,对Ruby一无所知。

所以这是公案:

# You need to finish implementing triangle() in the file 'triangle.py'
from triangle import *

class AboutTriangleProject2(Koan):
# The first assignment did not talk about how to handle errors.
# Let's handle that part now.
def test_illegal_triangles_throw_exceptions(self):
# Calls triangle(0, 0, 0)
self.assertRaises(TriangleError, triangle, 0, 0, 0)

self.assertRaises(TriangleError, triangle, 3, 4, -5)
self.assertRaises(TriangleError, triangle, 1, 1, 3)
self.assertRaises(TriangleError, triangle, 2, 4, 2)

下面是triangle.py

def triangle(a, b, c):
# DELETE 'PASS' AND WRITE THIS CODE

if a == b and b == c and c == a:
return 'equilateral'
if a == b or b == c or a == c:
return 'isosceles'
else:
return 'scalene'

# Error class used in part 2. No need to change this code.
class TriangleError(StandardError):
pass

我应该完成triangle()函数。

据我了解,try... except... 的功能类似于如果满足某些条件则执行某些操作,否则会出现异常。那么在我的情况下,我应该使用 if ... then raise TriangleError 还是 try... except ... ?它们之间有什么区别?

非常感谢!

最佳答案

请参阅以下答案:

def triangle(a, b, c):
# DELETE 'PASS' AND WRITE THIS CODE
if min([a,b,c])<=0:
raise TriangleError
x,y,z = sorted([a,b,c])
if x+y<=z:
raise TriangleError
if a==b and b==c and c==a:
return 'equilateral'
if a==b or b==c or a==c:
return 'isosceles'
else:
return 'scalene'

关于Python Koan 131 引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7398652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com