Reputation: 25
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!
Upvotes: 0
Views: 167
Reputation: 16905
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.
Upvotes: 4