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 :\

Nick Kobishev
  • 157
  • 4
  • 13

1 Answers1

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
Community
  • 1
  • 1
Joseph
  • 12,678
  • 19
  • 76
  • 115
  • thanks, I saw them when I was searching for helpful information. I suppose I'm having trouble understanding how exactly it works. – Nick Kobishev Oct 08 '13 at 20:28
  • @NickKobishev, I've updated my answer to include some code. Since you're learning, please ask questions if you don't understand. – Joseph Oct 08 '13 at 20:38
  • 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. – Nick Kobishev Oct 08 '13 at 20:41
  • `*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! – Joseph Oct 08 '13 at 20:43