Home > Software engineering >  Why isn't my function outputting the list i want it to
Why isn't my function outputting the list i want it to

Time:06-12

I want my function to output a list with ordered elements, but all it outputs is "none"

def sort(number):
    for i in range(len(number)-1, 0, -1):
        for x in range(i):
            if number[x]>number[x 1]:
                temp = number[x]
                number[x] = number[x 1]
                temp = number[x 1]
                return

number = [1,4,2,6,9,3,7,8,11,10]

sortednum = sort(number)
print(sortednum)

OUTPUT: none

CodePudding user response:

You have no return statement after the outermost for loop, so Python implicitly returns None. Even in the if statement, you're returning None (because you've written return and not specified a value to return), so there isn't any possibility of your function returning anything other than None.

Edit: You're sorting the list in place too, so it doesn't make sense to return something. Either create a new list with the sorted values and return that, or if you want to sort in place, then returning None would be the correct thing. Don't mix the two.

CodePudding user response:

python already has a sorting function here

This is how you could implement it:

number = [1, 4, 2, 6, 9, 3, 7, 8, 11, 10]

sortednum = number.copy() # Copy the list
sortednum.sort() # Sort the new list
print(sortednum)

I hope this helps!

  • Related