7. Strings in functions


#1

n = "Hello"

Your function here!

def string_function(s):
s="world"
return (n)+(s)

print string_function(n)

And it displays an error like this: Oops, try again. string_function('Waynes') returned 'Helloworld' instead of 'Waynesworld'. What is going on there are no such strings in this task.


#2

It's right there in your code.


#3

I solved it by just doing the following:

def string_function(s):
    return s + 'world'

print string_function(n)

#4

I guess I'm confused here. Why isn't it return n + 'world' ??


#5

I second this, I don't understand why s + "world" wouldn't work...


#6

I figured it out:

n = "Hello"

def string_function(s):
INDENT return s + "world"

print string_function(n)


#7

Some of the code that is posted in this thread has not been formatted. When posted code is not formatted, it is difficult for other users to read it. After code has been pasted into the editing window for posting, you can format it by selecting it, and then by clicking the </> button above the editing area. Alternatively, you can place three backquotes on the line before the code and three backquotes on the line after the code. This will enable us to see important details, such as the indentation and underscores. If you use the backquotes, your code will be color-coded, making it especially easy to read.


#8

thank you guys! I got it


#9

Did we ever figure out why it is supposed to be "return s" instead of "return n"?

I can get to the next lesson, but I'd like to know why.


#10

Ok this drove me nuts too. I hate when I can pass the lesson but not fully understand whats going on. I think I figured this one out though. First here is my working code.

    > n = "Hello"

    > # Your function here!
    > def string_function(s):
    >     return s + "world"


    > print string_function(n)

So as the program executes it first declares a variable n and sets it equal to the string "Hello". Next it defines a function string_function with the argument (s). When the function is called it will add whatever value is stored in s to the string "world". Think of s just as a placeholder that can be replaced. I don't know if it was setup this way to try and trick you or what but an easier way to understand it is to play with the code a bit.

s = "Hello"

# Your function here!
def string_function(s):
    return s + "world"


print string_function(s)

This code will do the exact same thing as the first one. I just replaced the variable n with s. Alternatively:

n = "Hello"
m = "Goodbye"

# Your function here!
def string_function(s):
    return s + "world"


print string_function(n)
print string_function(m)

will print out both Helloworld and Goodbyeworld. This helped me better grasp what is going on behind the scenes and I hope it helps you!