0

I have created a python function that should permanently change the string passed as argument to the function, by reversing it.

hello="hello"

def reverse(string):
  reversed_string=""
  for x in range(len(string)-1,-1,-1):
    reversed_string+=string[x]
  string=reversed_string

reverse(hello)

print (hello)

Yet it still prints "hello", on the last line. Why is it not changing the variable passed into it? It should print "olleh" on the last line.

lansXp
  • 13
  • 1
  • 6
  • 3
    `str` values are immutable. You can't modify one, and you can't change the value a variable used as an argument by assigning to a parameter name. – chepner Jun 19 '20 at 23:00
  • you never return anything from your function either – Craicerjack Jun 19 '20 at 23:01
  • 2
    You are not returning the 'olleh', you are passing the hello string to the function, it does it's thing and does not return it. The scope of 'string' only exists in the function, not the global hello veriable scope. When you print the variable hello, it is still the original (global) since you have not changed the original one. You would need to add ```return reverse_string``` and then assign it, ```hello = reverse(hello)``` – eddyizm Jun 19 '20 at 23:02
  • 1
    BTW there's an easier way to reverse a string: `hello = hello[::-1]`. It's basically the slice version of your `range` and loop. – wjandrea Jun 19 '20 at 23:03
  • My intention with this function is not to return anything. It is simply to permanently change the string argument that is passed to it. And you guys say strings are immutable yet if I did hello="hello", then hello="hey" and print (hello), I would get "hey". So clearly you can reassign strings. And in my function, that is what I am doing, reassigning the string variable. Yet it is not working. So I wonder why. – lansXp Jun 19 '20 at 23:05
  • 1
    Reassigning is different, that is just reusing the variable name to refer to something else (in this case a different string). The old string is not changed, and will be destroyed if nothing else is referring to it. – alani Jun 19 '20 at 23:07

0 Answers0