Practice Makes Perfect - Median - please help! Still stuck!


I am really stuck with this code please help me!!!


Hello! Let me try to help you! First of all, in order to make it more clear for us to understand your code, use the code formatting option (or Ctrl+Shift+C). Also, add to the post the error message you are receiving in the console.

So this is your code correctly formatted:

def median(numbers):
    new = sorted(numbers)
    A = int(len(new) / 2.0)
    if len(new) % 2 != 0:
        result = new[A] #here is the error.
    return result

As the console error message points out, the result variable that is inside the if loop wasn’t assigned before. So when it runs the code inside the if loop, it can’t assign new[A] to a non-existent variable. What you should do is create a result variable in the beginning of the function code as you did for the other ones. Here it is:

def median1(numbers):
    new = sorted(numbers)
    A = int(len(new) / 2.0)
    result = []
    if len(new) % 2 != 0:
        result = new[A]
    return result

This will solve your error. However, it won’t complete the lesson.


who can I change it to complete the lesson


I don’t give answers. You are on the right path, now you need to add the code in case the list has an odd number of items.


Ok but what format would I need to do


What do you think you should do now? You already sorted the list, you assigned a variable to the length of the list divided by 2, and created a loop in case the list has an odd number of items.

You also need to deal with the list when it has an even number of items and write the algorithm as explained in the lesson to find the median.


I need help I don’t know what to do I am still stuck!!


You just can’t say “I don’t know what to do.” You gotta give me something to work with. I won’t give you the answer. Try to code something and then bring it here.


I tried this code but it didnt work


Hmm… I see. Can you please post the formatted code so I can check it?


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.