Using strings in lists and funtions


I'm stuck on exercise 16, using strings in lists and functions

It doesn't return what I expect it too, this is the error

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

I expect it to join the two words together

n = ["Michael", "Lieberman"]
def join_strings(words):
    result= ""
    for i in range(len(words)):
        print words.append(result)
        return result

print join_strings(n).


the function ends the moment a return keyword is reached, which in your case happens in the first run of the loop, you might want to change the indent of your return so the whole loop can run

.append() is a built in function to append items to a list, not a string. and you use it wrong:


use += to join strings


one issue in python which is not observed in other languages (c / fortran / php / java etc) is "Strict Indentation". i wrote correct code ( can i dare 2 say code is correct if indentation is wrong). it did not work since indentation was not correct. if u have functions inside function with wrong indentation then u r gone.

pl correct me if i am wrong..


Thanks for the reply, but I'm afraid I am still stuck.

I don't understand when I should add the append command in my code

n = ["Michael", "Lieberman"]
def join_strings(words):
    result= ""
    for i in range(len(words):
        print words
    return result

print join_strings(n)


no, you are right, python relies on indention rather then brackets. So then indention becomes crucial


well, you should use += to join a string, rather then .append()

uhm... using range will give you indexes, so you would to use square brackets to use the index to access the item in the list. i will hold the index, you can also not use range and then it will have the actual list item


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