16.Using Strings In List Functions, Return Error. Need Help


#1



16./using Strings in list in functions. Return Error

https://www.codecademy.com/courses/python-beginner-nzzVa/3/5?curriculum_id=4f89dab3d788890003000096#


My code continually says:
File "python", line 8
SyntaxError: 'return' outside function


I expected it to go through the whole program but no matter what I do that error keeps popping up and I even looked at past examples and help forums and nothing has seemed to work.

What am I doing wrong?

Replace this line with your code. 
n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(words):
    result = [""]
for i in range(len(words)):
    result += words[i]
return result

print join_strings(n)


#2

Indentation is how Python recognizes scope. Without it, the interpreter cannot tell what is inside a block, and what is not. The first line in the block is correct, but the remaining three are not since they are not indented.

def join_strings(words):
    result = [""]
    for i in range(len(words)):
        result += words[i]
    return result

#3

Ok I indented and that slightly helped but now there's a new error.

Here's the error:
Oops, try again. join_strings(['x', 'y', 'z', 'a']) resulted in an error: 'list' object has no attribute 'join'

Here's my code:
n = ["Michael", "Lieberman"]

Add your function here

def join_strings(words):
result = [""].join(words)
for n in range(len(words)):
result += words[n]
return result

print join_strings(n)

#4

When initializing an empty list, do not include an empty string. That will occupy the first element when the list should be empty.

result = []

But in this exercise we don't need an empty list. We can simply return the joined list.

def join_strings(words):
    return " ".join(words)
"separator".join(list_object)

#5

Thanks a lot that really helped out and let me move along


#6

This thread has been useful, but can someone explain why append can't be used in this case?

E.g.:

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

print join_strings(n)

#7

Strings do not have an .append() method. Use an empty list to start.

result = []

However, in this case we already have a list to start and we want to create a string from it.

return " ".join(n)

is all we need in the function. If we wish to loop through and concatenate a string,

result = ""
for word in words:
    result += word
return result

#8

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