Do you understand what has happened here ? 16. Using strings in lists in functions


Oops, try again. join_strings(['x', 'y', 'z', 'a']) returned 'MichaelLieberman' instead of 'xyza'

Preview is showing me correct result but I get this odd error msg.

n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(words):
    result = ""
    for i in n:
        result = n[0] + n[1]
    return result

print join_strings(n)


you pass n as function argument:

print join_strings(n)

but then inside the function you should use the function parameter (words) to loop over (for loop), since the function parameter holds what you pass as argument when you call the function, this way your function works for everything you pass into the function when calling the function, instead of just a fixed list

Also, your loop. what if your list contains more then two items? you should append i to your result (i contains the items in the list, thanks to the for loop)


I wasn't happy with this bit either

result = n[0] + n[1]

but at least I got the result I was aiming for but obviously didn't earn me a pass. Need to work on it.


but thanks to your for loop:

for i in words:
   print i

you have access to all the items in the list, and you can just append them to result, this way, your code will work no matter how many items there are in the list


command 'append' works with the name of the list we want append (or add items in it)

therefore .... shouldn't this work ?

n = ["Michael", "Lieberman"]

def join_strings(words):
    result = ""
    for i in words:
        return result

print join_strings(n)


no, this shouldn't work. I was tricking you. I on purpose was using the word append rather then join. append() is a function which appends items to lists. you will need to approach it differently:

total = 0
test = 12345
for i in str(test):
    total = total + int(i)
print total

i need to use + to join the string (the demonstration above is with numbers, but it works the same for stings, can't do everything for you)

words, the function parameter contains your list:

n = ["Michael", "Lieberman"]
def join_strings(words):
    print words
print join_strings(n)

i in your for loop will contain the words, not the indexes. So no need for n[i]

You need to use the function parameter, given the exercise is going to test multiply lists.

if you insist on using indexes, you will have to use range()

careful with the indention of your return, again...


Would you review my code ?


you really should start using the function parameter in the for loop, so you can call the function with different lists, instead of just one fixed lists



This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.