0

I have a code like this:

>>> def enterText(value):
    command = input ("enter text: ")
    value = command

>>> def start():
    text = ""
    enterText(text)
    print ("you entered: "+str(text))

I have tied a lot of things but I can't seem to figure it out. I'm new to Python, can help me pass a string through functions? Thanks!

2
  • Did you want to return the command? Commented Jan 15, 2013 at 0:48
  • Yes, that's exactly what I want to do Commented Jan 15, 2013 at 0:52

1 Answer 1

4

Strings in Python are immutable. You need to return the string from enterText() so you can use it within start().

>>> def enterText():
    return input("enter text: ")

>>> def start():
    text = enterText()
    print ("you entered: " + str(text))

A given string object cannot be changed. When you call enterText(text), value will refer to the empty string object created within start().

Assigning to value then rebinds the variable, i.e. it connects the name "value" with the object referenced by the right-hand side of the assignment. An assignment to a plain variable does not modify an object.

The text variable, however, will continue to refer to the empty string until you assign to text again. But since you don't do that, it can't work.

Sign up to request clarification or add additional context in comments.

4 Comments

You would get the same rebinding behavior even if value was a mutable list. I think you should probably add something about local vs. global scopes to make this a complete answer. Nonetheless, +1.
@JoelCornett Which part would you rephrase? I didn't mean to make it sound like the rebinding only happens because strings are immutable.
It's not a huge deal. Your first sentence seems to imply that the immutability of strings is the reason why the assignment operation isn't working. The rest of your answer clarifies the point though.
@JoelCornett Ah yes, I can see what you mean. Maybe I'll come to think of a better wording.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.