Home > Mobile >  Trouble with Python returning a value
Trouble with Python returning a value

Time:08-12

I'm a beginner to writing Python programs and I'm struggling to write this particular exercise from https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/

In exercise 2, I'm to sort a list. This is what I have so far, but it keeps failing saying the order is not defined. I'm not sure where to define the functions so the if and elif statements trigger, any help is appreciated:


"""create a function with two parameters"""
def digits(num_list, order):
    if order == 'asc':
        print(digits(num_list.sort()))
    elif order == 'desc':
        print(digits(num_list.sort(reverse=True)))
    else:
        print(digits(num_list))


digit_list = [12, 15, 2, 7, 8, 25, 5, 45, 2]

digits(digit_list, 'asc')

CodePudding user response:

It seems your function is recursive, when you don't want it to be. On line 4, see how print(digits(num_list.sort())) is calling the digits function again- with no order parameter defined?

When a parameter is optional, it is best to give it as a keyword argument with a default value. Like order=None.

Also when you call list.sort, it sorts the list in-place returning no output. What you want here is the built-in sorted function, or call the list.sort before printing.

doc-strings should be put inside a function to come up when the help function is called upon the function.

This seems to be the code you were going after.

def digits(num_list, order=None):
    """create a function with two parameters"""
    if order == 'asc':
        print(sorted(num_list))
    elif order == 'desc':
        print(sorted(num_list, reverse=True))
    else:
        print(num_list)


digit_list = [12, 15, 2, 7, 8, 25, 5, 45, 2]

digits(digit_list, 'asc')

Please let me know how it went! Welcome to Python!

Edit: 2nd method with list.sort

def digits(num_list, order=None):
    """create a function with two parameters"""
    if order:
        num_list.sort(reverse=(order == 'desc'))
    print(num_list)


digit_list = [12, 15, 2, 7, 8, 25, 5, 45, 2]

digits(digit_list, 'asc')

CodePudding user response:

When you write a Python function, you often want it to return something (rather than print something).

Here is a function that returns the list (either sorted, reverse sorted, or without change).

"""create a function with two parameters"""
def digits(num_list, order):
    if order == 'asc':
        num_list.sort()
    elif order == 'desc':
        num_list.sort(reverse=True)
    return num_list

You can invoke the function with:

digit_list = [12, 15, 2, 7, 8, 25, 5, 45, 2]

digits(digit_list, 'asc')
  • Related