I’m going through the Python bits and it’s my first ever attempt at coding, so for this question we need to find the max number in a given list and return it, now the way I done it gave me the right answer but the check answer function came back incorrect.
I was just wondering if there is something obviously wrong with the way I coded it or if it’s ok?
So I done
def max_num(nums):
maxxed = 0
for num in nums:
if num > maxxed:
maxxed = num
else:
continue
return maxxed
print(max_num([50, -10, 0, 75, 20]))
The above gave me the correct answer of 75 from the list, but the check answer was going on about -20 and -50 returning 0?
Just want to make sure I’ve not done something wrong.
Would you be able to post a link to the challenge in question, this way I can test your code against the Codecademy challenge and see what it is flagging up exactly?
EDIT:
It’s alright I’ve found the question, and luckily it’s actually a very easy answer! What the error is saying is that if you called your function like so:
max_num([-50, -20])
then you get the result of 0 back as the max number. There’s a single line of code that needs changed to fix this, and as a hint, I would say recall point 2 of the question. For you and any other learners who may be struggling and just wish to see the resolution, I’ll include it in a spoiler tag below, but best to try yourself first.
The problem is with the initialisation of maxxed = 0. Codecademy runs fringe case tests like the above one in the background to make sure the function you have written is robust, and so this test case flagged that the wrong error was run. When you have a list of entirely negative numbers, these are all less than 0. Therefore if maxxed is initially set to 0, no number in that list can possibly be bigger, and so it will return 0. As such you need to initialise it to the first number in the list as point 2 on the page mentions, so that the comparisons are contained to the list and do not introduce external bugs. If you change this to maxxed = nums[0] then your function should be accepted.
Perfect, thank you! I was getting confused by the error as I had the right answer and couldn’t see -50 or -20 in the pre-written call
That makes sense, I took your hint and changed the default value and all is well.
Thank you again for the quick and helpful response!