1

new to python. couldn't figure out the answer to this question for 2 days now.. would appreciate some help, googling didn't help.

Fill in the "foo" and "bar" functions so they can receive a variable amount of arguments (3 or more) The "foo" function must return the amount of extra arguments received. The "bar" must return "True" if the argument with the keyword "magicnumber" is worth 7, and False otherwise.

# edit the functions prototype and implementation
def foo(a, b, c):
    pass

def bar(a, b, c):
    pass


# test code
if foo(1,2,3,4) == 1:
    print "Good."
if foo(1,2,3,4,5) == 2:
    print "Better."
if bar(1,2,3,magicnumber = 6) == False:
    print "Great."
if bar(1,2,3,magicnumber = 7) == True:
    print "Awesome!"

I guess.. some partial code will be good, having trouble understanding **kwargs and all that :\

2

1 Answer 1

5

I'm not sure if you just want someone to give you the code but since you've said you're trying to learn, I'll just point you in the right direction for now. You want to use Python's keyword arguments.

This and this should help you get started.

[Edit]

Here is the code:

def foo(a, b, c, *args):
    return len(args)

def bar(a, b, c, **kwargs):
    if kwargs["magicnumber"] == 7:
      return True
    return False
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, I saw them when I was searching for helpful information. I suppose I'm having trouble understanding how exactly it works.
@NickKobishev, I've updated my answer to include some code. Since you're learning, please ask questions if you don't understand.
thanks, I've seen some explanations about the difference of args and **kwargs, (**) but I don't seem to really understand when I should use which.
*args allows you a variable-number of arguments. With the foo example above, you must supply a, b, and c, and then you can also give it any other number of arguments. With **kwargs, you can pass in named arguments, as shown with the call to bar with magicnumber=7 above. If the answer I supplied solves your problem, please don't forget to mark it as correct, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.