从Python开始:从函数中查找最大数字,给出正整数的输入列表

时间:2016-08-01 18:19:54

标签: python

  1. python新手,无法让函数显示最大数字,由于某种原因,我的数字显示最少。 我正在使用的测验使用此代码作为最终解决方案,我认为这是错误的,任何帮助赞赏。

    # Define a procedure, greatest,
    # that takes as input a list
    # of positive numbers, and
    # returns the greatest number
    # in that list. If the input
    # list is empty, the output
    # should be 0.
    def greatest(list_of_numbers):
        big = 0 
        for i in list_of_numbers: 
            if i > big: 
                big = i
            return big 
    
    print greatest([4,23,1])
    #>>> 23  I can't get 23 It returns 4 for some reason. 
    print greatest([])
    #>>> 0
    

    出于某种原因,它给了我4而不是23最大。

1 个答案:

答案 0 :(得分:3)

您将在第一次迭代时返回。将您的回报移出一个级别:

def greatest(list_of_numbers):
    big = 0 
    for i in list_of_numbers: 
        if i > big: 
            big = i
    return big

然而,这完全没有必要,因为Python内置了这个:

def greatest(list_of_numbers):
    return max(list_of_numbers)