2010-09-17 48 views
0

假設你已經寫了一個新的函數來檢查你的遊戲角色是否有生命。如果角色沒有剩餘生命,則該功能應打印「死亡」,如果該功能的剩餘壽命點少於或等於5個,則該功能應打印「幾乎死亡」,否則應打印「活着」。這段代碼中的錯誤是什麼?

am_i_alive(): 
    hit_points = 20 
    if hit_points = 0: 
     print 'dead' 
    else hit_points <= 5: 
     print 'almost dead' 
    else: 
     print 'alive' 

am_i_alive() 
+0

你的單元測試用例在哪裏?如果你會寫一些測試用例,你會知道錯誤是什麼,不是嗎? – 2010-09-17 10:02:31

+0

@ S.Lott在代碼顯示的情況下,我會說它是它自己的單元測試;) – aaronasterling 2010-09-17 18:22:35

回答

8
def am_i_alive(): 
    hit_points = 20 
    if hit_points == 0: 
     print 'dead' 
    elif hit_points <= 5: 
     print 'almost dead' 
    else: 
     print 'alive' 

am_i_alive() 
  1. 您需要def關鍵字來定義一個函數。
  2. 您需要使用==而不是=進行比較。
  3. 如果使用elif表示陳述,則鏈接。

除此之外,它看起來不錯。在正確和將編譯。它將始終產生相同的價值。

一個更好的辦法來做到這一點是:

def am_i_alive(hit_points): 
    if hit_points == 0: 
     print 'dead' 
    elif hit_points <= 5: 
     print 'almost dead' 
    else: 
     print 'alive' 

am_i_alive(20) 
am_i_alive(3) 
am_i_alive(0) 

在這裏,我們傳遞一個「說法」的功能。我們稱之爲am_i_alive(x),其中x可以是任何數字。在函數am_i_alive的代碼中,無論我們用什麼來代替x都成爲hit_points所指的值。

函數也可以帶兩個參數。 (實際上最多255個參數)

def am_i_alive(hit_points, threshold): 
    if hit_points == 0: 
     print 'dead' 
    elif hit_points <= threshold: 
     print 'almost dead' 
    else: 
     print 'alive' 

am_i_alive(20, 5) 
am_i_alive(3, 2) 
am_i_alive(0, 10) 

您能理解上一個版本的作用嗎?

我沒有讀它,因爲蟒蛇不是我的第一語言,但我被告知這是一個非常好的introduction to python and programming

+0

哦!現在有道理!謝謝! – 2010-09-17 05:56:36

+0

您還需要'elif'而不是'else if'。 – 2010-09-17 06:02:57

+0

@Fred拉爾森。好看。我正在休息一些C編碼;) – aaronasterling 2010-09-17 06:04:58