-2
\$\begingroup\$

I tried so many things to do this task. I have no idea why doesn't it work. Please help!

'''Create a function in Python that accepts two parameters. The first will be a list of numbers. The second parameter will be a string that can be one of the following values: asc, desc, and none. 
If the second parameter is "asc," then the function should return a list with the numbers in ascending order. If it's "desc," then the list should be in descending order, and if it's "none," it should return the original list unaltered '''

def func(*args, str):
    list1=args
    if str == 'asc':
        a = sorted(list1,reverse=False)
        print(a)
    elif str == 'desc':
        b = sorted(list1,reverse=True)
        print(b)
    else:
        print(list1)
     

l = [2,3,7,6,5]    
m = 'asc'
print(func(l,m))

I know that I also have to do 'none' for str, but I don't know how

\$\endgroup\$
1
  • 3
    \$\begingroup\$ This site is for reviewing working code. You might want to ask for help on Stack Overflow. Although in this case it's trivial: you're supposed to return from this function. Replace all the print(...) in your function code with return .... And your *args parameter should just be args. \$\endgroup\$ Commented Oct 23, 2022 at 22:58

1 Answer 1

-3
\$\begingroup\$

Ok so when you do

function(*args, str):
    ...

args collects all positional arguments, str then becomes a keyword only argument. Since you pass the values as a single list instead of multiple single values you don't even need the *

function(args, str): # will work just fine
    ....

Another thing not directly related to the functionality of this specific code is that you really shouldn't use built-in names like that, even though here it's limited to the function scope.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Welcome to Code Review, but you shouldn't answer off-topic questions. \$\endgroup\$ Commented Oct 23, 2022 at 23:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.