0
makebbb(a):
    a = "bbb"

this function obviously fails to convert it's input to "bbb" as demonstrated by the following snippet

x = "notbbb"
makebbb(x)
print(x)
# Outputs "notbbb"

Now I understand the reason this fails, what I wish to find out is if there is anyway to make such a function? (I'm not just talking about assigning strings, but assignment with = in general)

Rufus
  • 5,111
  • 4
  • 28
  • 45
  • read up on mutable and immutable arguments in python. you can not change immutable arguments. (you could hack your way around it by putting them in a list or declaring them global). there are many questions about just that here. – hiro protagonist Dec 30 '16 at 06:54
  • `def makebbb(a="bbb"):return a` than `print makebbb("test")`, Local initial value for changeable or static variable – dsgdfg Dec 30 '16 at 07:09

5 Answers5

0

Define the variable you want to change from a func as global ,

>>> def makebbb():
    global x
    x = "bbb"


>>> print x
notbbb
>>> makebbb()
>>> print x
bbb
>>>
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

why not simply return a value in your function and update 'a'?

def makebbb(a):
    return "bbb"

x = "notbbb"
x = makebbb(x)
print(x)
Shobeir
  • 127
  • 7
0
def makebbb(a):
    return "bbb"

x = "notbbb"
x = makebbb(x) #call function in the assignment to modify it 
print(x)

Output:

bbb
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44
0

If x exists outside the scope of the function, you can modify the variable directly (rebind values to the same variable in memory). Otherwise, a functional approach would be to just return a new string.

x = "notbbb"
makebbb() # Modify variable outside function scope.
print(x)

or

x = "notbbb"
print(makebbb(x)) # return new value.    

The particular catch with this example is that you are trying to pass a an immutable value by reference. What happens instead is that a copy is created on argument passing. You can achieve the effect you want with mutable types such as lists though.

ospahiu
  • 3,465
  • 2
  • 13
  • 24
0

You can modify some arguments, those that are passed by reference instead of by value.

Arguments that are mutable objects can be changed, like so:

def change_list(l):
    l.append(4)

k = [1, 2, 3]
change_list(k)
print(k)   # Prints [1,2,3,4]

This, however, will not work:

def dont_change_list(l):
    l = [5]
zmbq
  • 38,013
  • 14
  • 101
  • 171