0

I'm new to python and I'm currently styding it, more specifically how to create functions; in this piece of code, I'm supposed to create a function that concatenates all of the arguments given in a single sentence.

def concatenate_all(**kwargs):
    """Gets any number of strings and concatenate them all in a single sentence, separating them with spaces"""
    concat_str = ""
    for string in kwargs.items(): 
        concat_str = concat_str + kwargs.keys(string)
        return concat_str

This tests if my function is working as requested or not by showing True or False
    print(concatenate_all("I", "did", "it") == "I did it ")
    print(concatenate_all("I", "did", "it", "again", "!!!") == "I did it again !!! ")

and I'm getting this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-cd1682a7625a> in <module>()
      6         return concat_str
      7 
----> 8 print(concatenate_all("I", "did", "it") == "I did it ")
      9 print(concatenate_all("I", "did", "it", "again", "!!!") == "I did it again !!! ")

TypeError: concatenate_all() takes 0 positional arguments but 3 were given

I'm not quite sure why... (?????) I mean, the arguments were provided, it's almost as if it's not recognizing the **kwargs attribute... Any thoughts? Thanks in advance! :)

  • 5
    Does this answer your question? [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) – buran Mar 24 '22 at 19:41
  • @NathanLiang, actually their function accepts arbitrary number of **keyword** arguments. Also make the dicstinction between [parameter](https://docs.python.org/3/glossary.html#term-parameter) and [argument](https://docs.python.org/3/glossary.html#term-argument) – buran Mar 24 '22 at 19:43
  • You are not providing key words, but arguments – baskettaz Mar 24 '22 at 19:45
  • Side note: your `return` is _inside_ the loop so the function ends at the end of the first iteration. – 001 Mar 24 '22 at 19:46
  • Thanks for the answers, folks! I hadn't noticed about the return being inside the loop, thanks for the insight @JohnnyMopp!! – Talita Mar 24 '22 at 20:20

1 Answers1

0

You shouldn't use **kwargs for it.**arg_name(doesn't have to be "kwargs") is used to send all the keyword arguments passed to a function as a dictionary.you can however use the splat operator(*) inside function parameter,which will send all you function arguments as a tuple.i.e

def concatenate(*args):
    concatenated_str = ''
    for arg in args:
        concatenated_str += arg
    return concatenated_str

concatenate('I', ' Like', ' Apples') == "I Like Apples"
Justaus3r
  • 395
  • 5
  • 15