2011-09-13 144 views
2

我正在通過Python Koans學習Python,並且提出了在Python中引發異常的問題。具體來說,我經歷了koan後甚至與try...except...混淆。我知道對Rudy Koan Ruby Koan 151 raising exceptions有類似的問題。但我是一個Python新手,對Ruby一無所知。Python Koan 131引發異常

因此,這裏的公案:

# 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 ...?他們之間有什麼不同?

非常感謝!

回答

1

您想要使用raise,這會導致創建一個異常,並沿着調用堆棧向前移動,直到通過try/except塊處理異常爲止。例如,如果你在真正的代碼中使用此三角函數,你會做這樣的事情

try: 
    t = triangle(x, y, z) 
    ... 
except TriangleError: 
    print 'Triangle', x, y, z, 'is no good!' 

這樣,你能處理錯誤時壞的三角形被做和你的程序將不會崩潰。

4

請看下面的答案:

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'  
1

這裏是我的代碼,它的工作

def triangle(a, b, c): 
# DELETE 'PASS' AND WRITE THIS CODE 
if min([a,b,c])<=0: 
    raise TriangleError,"no <0 numbers" 

if sorted([a,b,c])[0]+sorted([a,b,c])[1]<=sorted([a,b,c])[2]: 
    raise TriangleError,"sf" 

set_a=set(([a,b,c])) 
if len(set_a)==1: 
    return 'equilateral' 
elif len(set_a)==2: 
    return 'isosceles' 
elif len(set_a)==3: 
    return 'scalene' 

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

我結束了類似南希的答案的東西,使用集,而不是比較A,B和手動,並且它也可以工作。

def triangle(a, b, c): 
    # DELETE 'PASS' AND WRITE THIS CODE 
    ls = sorted([a,b,c]) 
    if min(ls)<=0 or ls[0]+ls[1]<=ls[2]: raise TriangleError, 'Triángulo mal formado.' 
    l = len(list(set(ls))) 
    if(l==1): return 'equilateral' 
    if(l==2): return 'isosceles' 
    if(l==3): return 'scalene' 

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