1

Hello I was wondering why using **kwargs is not working in this example. I was following the answer as given in Alternating letter in python

def myfunc(**kwargs):
    return "".join(w.upper() if i%2 else w.lower() for i,w in enumerate(kwargs))

I have tried calling the function as myfunc("skyscraper") but get the error:

TypeError: myfunc() takes 0 positional arguments but 1 was given

Its probably something simple but not obvious to me. In the exercise says I am not allowed to use print statements and the function as to return a string Thanks

yong_m
  • 13
  • 3
  • `**argumentname` gives your function all unmatched arguments that were passed by keyword as a dictionary. – Steven Rumbalski Jun 07 '19 at 16:59
  • 1
    Possible duplicate of [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – manveti Jun 07 '19 at 17:00
  • you need to define a argument and use the name fo the argument to access the value. see my answer @yong_m – Devesh Kumar Singh Jun 07 '19 at 17:21

2 Answers2

0

**kwargs deals with keyword arguments. try using:

myfunc(somekeyword="skyscraper") 
paul
  • 408
  • 2
  • 8
  • Hi Paul, I am not sure though how could I change the function I've define to include this keyword I have tried defining inisde the function ``` python result = "".join(w.upper() if i%2 else w.lower() for i,w in enumerate(kwargs))``` and return result but that has not work. – yong_m Jun 07 '19 at 17:13
  • @yong_m: you need to change the call, not the function itself – paul Jun 07 '19 at 17:24
0

You would need to pass a keyword argument to the function e.g. myfunc(arg="skyscraper"), and then use the name of the keyword argument in the function to extract out the value.

For example

def myfunc(**kwargs):
    #arg is the name of the argument, you extract the value from the kwargs dictionary
    return "".join(w.upper() if i%2 else w.lower() for i,w in enumerate(kwargs['arg']))

#Call myfunc using kwargs
print(myfunc(arg="skyscraper"))

The output will be

sKyScRaPeR
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40