Reputation: 107
New to python, having trouble getting the function to display the greatest number, for some reason I have the number display the least. The quiz I am using used this code as the final solution, I think it is wrong, any help appreciated.
# 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
For some reason it gives me 4 instead of 23 as the greatest.
Upvotes: 0
Views: 207
Reputation: 11049
You are returning on the first iteration. Move your return out one level:
def greatest(list_of_numbers):
big = 0
for i in list_of_numbers:
if i > big:
big = i
return big
However this is entirely unnecessary as Python has this built in:
def greatest(list_of_numbers):
return max(list_of_numbers)
Upvotes: 3