2012-10-03 71 views
-3

我有一個任務來修復程序中的錯誤,我不知道該如何去做以及從哪裏開始。如何找到並修復錯誤

#this function takes, as input, a list of numbers and returns the list with the following changes: 
# if the original value in the list is positive, the value is doubled 
# if the original value in the list is negative, the value is tripled 
# if the value in the list is 0, then the value is replaced with the string 「zero」 
# for example, the result from timesTwo([1, 5, -2, 4, 0, -5, 3]) should be [2,10,-6,8,’zero’,-15,6] 
def timesTwo(myList): 
    counter = 0 
    while (counter <= len(myList)): 
     if (mylist(counter) > 0: 
      myList[counter] = myList[counter * 2] 
     counter = counter + 1 
     elif (myList[counter] < 0): 
      myList[counter] = myList[counter * 3] 
     counter = counter + 1 
     else: 
      myList[counter] = 「zero」 
    return myList 
+0

你的意思是除了編寫它試圖在文字處理器中編寫Python代碼的人嗎? – geoffspear

+1

使用調試,逐行逐行瀏覽並觀察所有變量。一般來說,從哪裏開始將「學習更多的Python」,答案將變得清晰,我敢肯定。 –

+0

你不需要括號(即'('和')'),while和if語句。你似乎在第一個'if'中混淆了你自己,只有'('沒有匹配的paren,然後使用parens而不是括號(例如'['和']')。嘗試去除這些測試中的parens ,而且錯誤會變得更清晰可見。 – tehwalrus

回答

1

什麼樣的錯誤?

如果它們是非常容易的異常。 Python通過完整的回溯告訴你發生異常的那一行。

如果它們是比較困難的邏輯錯誤。使用pdb非常自由的python調試器將有助於調試打印語句。只需採用一般分析方法。如果結果不是你所希望通過線整個程序行步與pdb如果有必要

0

要添加到其他人所說,你也可以測試程序說什麼是應該做的。例如,給它列出一些正數,如[1,2,3],並確保輸出是[3,6,9]。

0

要找到邏輯錯誤,請嘗試編寫一些測試。你知道函數應該如何表現,所以試着想想各種輸入,看看函數是否給你預期的輸出。

例如

myList = [1,2,3] 
expectedList = [2,4,6] 

result = timesTwo(myList) 

print("The lists are the same size: " + len(expectedList) == len(result)) 
for(i = 0, i < len(expectedList), i++): 
    print("The element at position " + i + " is " + result[i] + " and should be " expectedList[i]) 

語法和異常應該告訴你哪一行錯誤的來源。

+0

DEF timesTwo2(myList中): resultList = [] 計數器= 0 而計數器 0: resultList.append(I * 2) 計數器+ = 1 if i <0: resultList.append(i * 3) if i == 0: resultList.append(「zero」) return resultList – user1701501

相關問題