-1

How can I get this function:

def test(var1):
    var1=5
a=0
test(a)
print(a)

To set variable a to equal 5.

Spacenaut
  • 549
  • 1
  • 4
  • 4

3 Answers3

1

You'll have to use a mutable variable, for example a list. This does something similar.

def test(var1):
    var1[0]=5
a=[0]
test(a)
print(a[0])
Brad Budlong
  • 1,775
  • 11
  • 10
0

You probably want to return the value:

def test(var1):
    var1 = 5
    return var1
a = 0
a = test(a)
print(a)
desired login
  • 1,138
  • 8
  • 15
0

Yes..Brad is correct...But a small correction there. We should say it as mutable object. When you use a mutable object like List, Dictionary you will achieve this..

>>> def test(var1):
...  var1.append(5)
 ...
>>> a=[]
>>> test(a)
>>> a
[5]

whereas, When you use immutable object like integer, string, tuple it wont change the value referenced by the object.

>>> def test(val1):
...  val1+(1,)
...
>>> test(a)
>>> a
()