I am trying to create a function named make_string, that uses * correctly with a parameter: strings The function should return a string of all the values supplied joined, and separated by a space. Outside the make_string function, I declare a variable named my_string, and assign the value returned from the make_string function. Then I call the make_string function with the following values: “Alderaan”, “Coruscant”, “Dagobah”, “Endor”, “Hoth”. Finally I print the value of my_string to the terminal…and it returns None, when it should return Alderaan Coruscant Dagobah Endor Hoth Can anybody tell me where I am going wrong please?
def make_string(*strings): my_string = "" for x in strings: my_string = x.join(strings) return my_string my_string = make_string() make_string("Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth") print(my_string)
Advertisement
Answer
There are a few things going on in your code that are a little wonky.
- You’re constantly re-assigning the value of
my_string
every time you loop throughfor x in strings
- There’s no reason to start with a blank string here since you’re already using
join
- Your function call isn’t setting to
my_string
— it isn’t set to anything. What you want is likemy_string = make_string("Bob", "Mary")
etc.
This should do the trick:
def make_string(*strings): return " ".join(strings) my_string = make_string("Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth") print(my_string)
Personally, I would say you don’t even need a function here, especially if you can easily set what you’re using for *strings
to a variable. For example:
planets = ["Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth"] print(" ".join(planets))