我有一个修复程序错误的任务,我不知道该怎么做以及从哪里开始。
#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 :(得分:1)
出现什么样的错误?
如果它们是非常简单的例外。 Python告诉您使用完整的回溯在哪一行上发生异常。
如果它们是更难的逻辑错误。非常自由地使用pdb
python调试器将有助于调试打印语句。这只是一种通用的分析方法。如果结果不是您希望在必要时逐行完成整个程序{/ 1}}
答案 1 :(得分:0)
要添加其他人所说的内容,您还可以测试该程序所说的内容。例如,只需给它一些像[1,2,3]这样的正数列表,并确保输出为[3,6,9]。
答案 2 :(得分: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] )
语法和异常应告诉您错误来自哪一行。