2013-11-15 63 views
0

編輯:更改條件..謝謝嘗試和除了在Python中,意外的輸出

我想學習嘗試/例外。我沒有得到我應該的輸出。它通常使一杯或沒有。理想情況下,應使9或10

說明:

創建NoCoffee類,然後寫一個函數調用make_coffee是執行以下操作:使用隨機模塊與95%的概率被創造了一壺咖啡打印消息並正常返回。有5%的機會,提高NoCoffee錯誤。

接下來,編寫一個函數attempt_make_ten_pots,它使用try塊和for循環來嘗試通過調用make_coffee來製作十個鍋。函數attempt_make_ten_pots必須使用try塊來處理NoCoffee異常,並且應該爲實際製作的罐數返回一個整數。

import random 

# First, a custom exception 
class NoCoffee(Exception): 
    def __init__(self): 
     super(NoCoffee, self).__init__() 
     self.msg = "There is no coffee!" 

def make_coffee(): 
    try: 
     if random.random() <= .95: 
      print "A pot of coffee has been made" 

    except NoCoffee as e: 
     print e.msg 

def attempt_make_ten_pots(): 
    cupsMade = 0 

    try: 
     for x in range(10): 
      make_coffee() 
      cupsMade += 1 

    except: 
     return cupsMade 


print attempt_make_ten_pots() 

回答

3
  1. 如果你想允許95%,那麼情況應該已經

    if random.random() <= .95: 
    
  2. 現在,爲了使你的程序拋出一個錯誤,並返回做咖啡的數量,你需要當隨機值大於.95時應引起例外,並且函數中不應包含make_coffee本身。

    import random 
    
    # First, a custom exception 
    class NoCoffee(Exception): 
        def __init__(self): 
        super(NoCoffee, self).__init__() 
        self.msg = "There is no coffee!" 
    
    def make_coffee(): 
        if random.random() <= .95: 
         print "A pot of coffee has been made" 
        else: 
         raise NoCoffee 
    
    def attempt_make_ten_pots(): 
        cupsMade = 0 
        try: 
         for x in range(10): 
          make_coffee() 
          cupsMade += 1 
        except NoCoffee as e: 
         print e.msg 
        return cupsMade 
    
    print attempt_make_ten_pots() 
    
+0

不要忘了返回'cupsMade'即使所有嘗試都成功。 – user2357112

+0

@ user2357112謝謝:)現在修復它 – thefourtheye