我的任务需要一些帮助:
Using a for loop, write a function called getMax4 that takes in a list of numbers. It determines and returns the maximum number that is divisible by 4. The function returns -999 if the argument is an empty list The function returns 0 if no number in the argument list is divisible by 4.
下面显示了调用函数时的输出示例:
在我的代码中,我成功地做到了以下几点:
def getMax4(list):
highest = 0
if len(list) == 0:
return -999
else:
for number in list:
if number % 4 == 0:
if number < highest:
highest = number
else:
highest = 0
return number
print(getMax4([]))
print(getMax4([1, 3, 9]))
print(getMax4([-4, 3, -12, -8, 13]))
print(getMax4([1, 16, 18, 12]))
我的结果如下:
我不明白为什么这个值被确定为None
,而它应该是0
。你知道吗
还有一点需要提醒的是,不要使用内建名称作为变量,例如
list
、str
、int
、float
、tuple
、type
,如果您稍后将这些内建作为函数调用,会给您带来糟糕的结果。所以我建议你把清单改成数字。你知道吗因为它只在if语句中出现
return number
:要返回0:
只需将
return number
标识到for循环。你知道吗比如
只是对现有代码的一个小更改,返回0以显式添加。你知道吗
我们来看看代码的执行情况。你知道吗
最明显的情况是长度为零的列表,它可以正确地处理它们。呜呼。你知道吗
另一个明显的例子是一个数字可以被4整除的列表。让我们看看:
所以我们已经确定了几个问题,包括一旦我们找到一个可以被4整除的数,我们就返回这个数作为解,尽管这里的正确答案是20。这显然是错误的!你知道吗
让我们介入并解决这些问题。你知道吗
现在,让我们用新代码完成同一个调用
现在我们可以看一下清理一下:
相关问题 更多 >
编程相关推荐