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

开始Python:从给出正整数输入列表的函数中查找最大数,python,Python,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 outp

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作为最伟大的


您将在第一次迭代中返回。将您的返回移出一级:

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) 

您将在第一次迭代中返回。将您的返回移出一级:

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) 

在python中,缩进很重要。由于
returnbig
在您的循环中,它将返回大于
0
的第一个值,即
4
。将
return big
向左移动1个选项卡;)很好,直到现在才有这个问题,谢谢!在python中,缩进很重要。由于
returnbig
在您的循环中,它将返回大于
0
的第一个值,即
4
。将
return big
向左移动1个选项卡;)很好,直到现在才有这个问题,谢谢!